真分页后端实现--Mybatis

首先,我们要真分页查询文件

然后,由于文件数据很多,我们设计了根据文件名称模糊查询文件的功能

由于采取了分页,需要根据查询出来的总的文件数来判断到底有几页

根据上面的几个需求,我们写了三个接口:

1.真分页查询每一页的数据

2.根据文件名真分页模糊查询

3.查询文件总数

优化:

三个合成一个

实现:

定义一个基础分页类basePage(好处:任何需要分页的地方只要继承这个基础分页类即可):

//@Data可以为类提供读写功能,从而不用写get、set方法;他还会为类提供 equals()、hashCode()、toString() 方法。
//使用方法:
//1.下载lombok插件
//2.重启idea
//3.maven库中添加依赖
//<dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
     <version>1.16.10</version>
  </dependency>
//4.在实体类上添加@Data注解即可生效
@Data
public class basePage {
    private Integer pageNum=1;
    private Integer pageSize=10;
    private String orderBy;
}

InformationEntity:

InformationEntity继承basePage

@Data
@TableName("t_information")
//实现Serializable接口的目的是为类可持久化,在网络传输或本地存储,为系统的分布和异构部署提供了先决条件。若没有序列化,现在我们所熟悉的远程调用,对象数据库都不可能存在
public class InformationEntity extends basePage implements Serializable  {
    //serialVersionUID适用于java序列化机制
    //JAVA序列化的机制是通过 判断类的serialVersionUID来验证的版本一致的。在进行反序列化时,JVM会把传来的字节流中的serialVersionUID于本地相应实体类的serialVersionUID进行比较。如果相同说明是一致的,可以进行反序列化,否则会出现反序列化版本一致的异常,即是InvalidCastException。
    //serialVersionUID有两种显示的生成方式:
    //一是默认的1L,比如:private static final long serialVersionUID = 1L;        
    //二是根据包名,类名,继承关系,非私有的方法和属性,以及参数,返回值等诸多因子计算得出的,极度复杂生成的一个64位的哈希字段。基本上计算出来的这个值是唯一的。比如:private static final long  serialVersionUID = xxxxL;
    private static final long serialVersionUID = 1L;

    /**
     * 文件id
     */
    @TableId
    private String id;
    /**
     * 项目id
     */
    private String projectId;
    /**
     * 文件名称
     */
    private String name;
    /**
     * 文件地址
     */
    private String url;
    /**
     * 文件类型
     */
    private String  type;

}

VideoListModel:

@Data


//注解在类上,为类提供一个无参的构造方法。
//与之相对应的还有两个:
//@AllArgsConstructor:注解在类上,为类提供一个全参的构造方法。
//@RequiredArgsConstructor:注解在类上,会生成构造方法(可以带参数也可以不带参数)。
@NoArgsConstructor

//生成setter方法返回this(也就是返回的是对象),代替了默认的返回void。
//加了Accessors(chain = true)   
public Devolution setCenterId(Long centerId) {
        this.centerId = centerId;
        return this;
}
//没加Accessors(chain = true)   
public void setCenterId(Long centerId) {
        this.centerId = centerId;
}
@Accessors(chain = true)


//如果domain中没有重写toString, 且使用了@Data注解, 调用toString时只会打印子类本身的属性值, 如果想要打印父类的属性:
//方式一: 重写tostring
//方式二: 子类加上@Data和@ToString(callSuper = true)两个注解, 父类也使用注解@Data
@ToString(callSuper = true)


public class VideoListModel {
    @ApiModelProperty(value = "视频列表")
    private List<InformationEntity> informationData;

    @ApiModelProperty(value = "视频总数")
    private Integer informationCount ;
}

controller层:

@ApiOperation(value = "查询文件列表")
    @PostMapping("selectInformations/")
    public InformationResult selectInformations(@RequestBody InformationEntity informationEntity){
    VideoListModel videoListModel= videoInformationService.selectInformations(informationEntity)
    if(!null=videoListModel){
        return InformationResult.build(InformationResult.SUCCESS,msg:"查询成功",videoListModel);
    }else{
        return InformationResult.build(InformationResult.FAIL,msg:"查询失败");
    }

service层:

VideoListModel selectInformations(InformationEntity informationEntity);

serviceImpl层:

 @Override
    public VideoListModel selectInformations(InformationEntity informationEntity) {
        //分页查询数据(有/无文件名)
        List<InformationEntity>Information = videoInformationDao.selectInformations(informationEntity);
        //实例化我们最后返回前端的model
        VideoListModel result=new VideoListModel();
        //查询文件总数
        Integer count = videoInformationDao.videototalByName (informationEntity);
        //model赋值
        result.setInformationData(Information);
        result.setInformationCount(count);
        return  result;
    }

dao层:

//分页查询数据(有/无文件名)
List<InformationEntity> selectInformations(InformationEntity informationEntity);
//查询文件总数
Integer videototalByName(InformationEntity informationEntity);

mapper层:

//查询文件总数
<select id="videototalByName" parameterType="com.tfjybj.lap.video.entity.InformationEntity" resultType="java.lang.Integer">
        select
        count(id)
        from
        t_information
</select>
 //分页查询数据(有/无文件名)
<select id="selectInformations" parameterType="com.tfjybj.lap.video.entity.InformationEntity" resultType="com.tfjybj.lap.video.entity.InformationEntity">
        select
            id,
            project_id,
            name,           
            url,
            type
        from
            t_information
        where
              1=1
            <if test="name!=null and name!=''">
            and name like ('%${name}%')
            </if>
            <if test="orderBy !=null and orderBy!=''">
              order by ${orderBy}
            </if>
             <bind name="pageNum" value="(pageNum-1)*pageSize"></bind>
            limit ${pageNum},${pageSize}
</select>

下面,给大家说一下Mybatis的动态sql:

Mybatis的动态sql分为下面几类:

1、动态SQL:if 语句
2、动态SQL:if+where 语句
3、动态SQL:if+set 语句
4、动态SQL:choose(when,otherwise) 语句
5、动态SQL:trim 语句
6、动态SQL: SQL 片段
7、动态SQL: foreach 语句

我们今天用到的是第一个if语句:

假设一个场景,根据name和sex来查询数据。

不使用动态sql来写:

 select * from user where name=#{name} and sex=#{sex}

如果此时name为空或者sex为空,这个sql语句就会有问题,此时怎么办呢?使用动态sql的if

 select * from user where
        <if test="name != null">
           name=#{name}
        </if>
         
        <if test="sex!= null">
           and sex=#{sex}
        </if>

如果 sex 等于 null,那么查询语句为 select * from user where name=#{name},但是如果usename 为空呢?那么查询语句为 select * from user where and sex=#{sex},这是错误的 SQL 语句,如何解决呢?用动态sql的where

这个大家可以下面去看看,本业务场景不涉及,哈哈哈哈哈哈哈哈哈哈

下面说一下Mybatis的bind标签:

首先,为什么要用bind标签呢:

mysql基本分页语句:

select * from table limit pageNum,pageSize

正常情况下是没有问题的

但是,如果pageNum是动态的,mysql就无法识别了 

select * from table limit (pageNum-1)*pageSize,pageSize

解决方案(推荐使用bind标签) :

 <bind name="pageNum" value="(pageNum-1)*pageSize"></bind>
 limit ${pageNum},${pageSize}

bind标签解析:bind标签中,value对应传入实体类的某个字段,name属性既给对应字段取的变量名。在value属性中可以使用字符串拼接等特殊处理。

分页原理解析:

假设你每页显示10条,第一页:0-9,第二页:10-19,第三页:20-29。

然后你在根据规律计算的出来的规律就是startIndex=(pageindex - 1) * pagesize;

第一页的开始记录是:(1-1)*10=0;范围:0~9

第二页的开始记录是:(2-1)*10=10 ;范围:10~19

......

其实,关于分页,Mybatis还给我们提供了一个非常好的分页插件--PageHelper

简介:PageHelper是Github上开源的MyBatis分页插件,使用起来非常的简单,方便,并且支持任何复杂的单表、多表分页。

官网:https://pagehelper.github.io/

Github网址:https://github.com/pagehelper/Mybatis-PageHelper/blob/master/README_zh.md

使用步骤:

1.pom添加依赖

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>

2.使用

i.controller层

//controller层使用  
@RequestMapping(value ="/all",method = RequestMethod.GET)
    public PageInfo<OrderInfo> getAllOrders(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                                            @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        return orderService.getAllOrders(pageNum,pageSize);
    }

ii.serviceImpl层

//serviceImpl层调用
 public PageInfo<OrderInfo> getAllOrders(int page, int pageSize){
        PageHelper.startPage(page, pageSize);
 }

既然这么方便,为什么我们没有使用呢???这个需要思考一下

猜你喜欢

转载自blog.csdn.net/hejingfang123/article/details/119000689