4.1 MyBatis 分页插件
分页查询基本上是必备的能力,MyBaits 可以通过插件来很好的支持分页查询,目前最成熟的方案是pagehelper这个第三方插件。
我们只需要在工程的 pom.xml 里添加如下的依赖即可,目前最新的版本是1.2.13
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.13</version>
</dependency>
pagehelper 非常易用,内部做了很多的优化工作,让开发者基本不需要额外处理 MyBatis XML 逻辑,我们通过代码来看一下,继续改造 UserController.getAll 方法
package com.youkeda.comment.control;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.youkeda.comment.dao.UserDAO;
import com.youkeda.comment.dataobject.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
@Controller
public class UserController {
    @Autowired
    private UserDAO userDAO;
    @GetMapping("/users")
    @ResponseBody
    public List<UserDO> getAll() {
        // 设置当前页数为1,以及每页3条记录
        Page<UserDO> page = PageHelper.startPage(1, 3).doSelectPage(() -> userDAO.findAll());
        return page.getResult();
    }
}
如上,我们使用PageHelper类来处理分页,它的完整包名是
com.github.pagehelper.PageHelper
我们结合 lambda 语法,在doSelectPage lambda 方法中执行 MyBatis 查询方法,就会自动执行分页逻辑,并且返回分页对象Page,我们在仔细看看方法调用的情况
PageHelper.startPage(1, 3);
startPage第一个参数是指定页数,第二个参数指定的是每页的记录数
MyBatis PageHelper 比较智能,如果查询第0页会自动转化为查询第一页(让开发者不纠结这个坐标值),如果查询的页数超过总页数也会自动查询最后一页。比如下面的调用和上面是一样的
PageHelper.startPage(0, 3);
返回类型Page对象是 MyBatis 封装的分页模型,通过这个我们可以得到
- getResult()获取分数数据
- getPages()获取总页数
- getTotal()获取总记录数
- getPageNum()获取当前页面数
Page的完整路径是com.github.pagehelper.Page
在企业开发中,我们都会额外封装一个通用的分页模型Paging用于处理返回值,参考如下
以后我们再各种项目中可能会经常复用这个模型,就不再额外介绍啦
package com.youkeda.comment.model;
import java.io.Serializable;
import java.util.List;
/**
 * 分页模型
 */
public class Paging<R> implements Serializable {
   /*
   R可以是任何类型,比如CommentDO、UserDO等,具体取决于你在使用Paging类时传入的类型。
   */
    private static final long serialVersionUID = 522660448543880825L;
    /**
     * 页数
     */
    private int pageNum;
    /**
     * 每页数量
     */
    private int pageSize = 15;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 总记录数
     */
    private long totalCount;
    /**
     * 集合数据
     */
    private List<R> data;
    public Paging() {
    }
    public Paging(int pageNum, int pageSize, int totalPage, long totalCount, List<R> data) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.totalPage = totalPage;
        this.totalCount = totalCount;
        this.data = data;
    }
    // 省略 getter、setter
}
Paging 模型比较简单,主要提供
- 
pageNum当前页面数
- 
pageSize每页记录数
- 
totalPage总页面数
- 
totalCount总记录数
- 
data当前页面的集合数据 我们还提供了一个构造函数public Paging(int pageNum, int pageSize, int totalPage, long totalCount, List<R> data)
我们继续改造一下 UserController.getAll 方法
package com.youkeda.comment.control;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.youkeda.comment.dao.UserDAO;
import com.youkeda.comment.dataobject.UserDO;
import com.youkeda.comment.model.Paging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.List;
@Controller
public class UserController {
    @Autowired
    private UserDAO userDAO;
    @GetMapping("/users")
    @ResponseBody
    public Paging<UserDO> getAll() {
        // 设置当前页数为1,以及每页3条记录
        Page<UserDO> page = PageHelper.startPage(1, 3).doSelectPage(() -> userDAO.findAll());
        return new Paging<>(page.getPageNum(), page.getPageSize(), page.getPages(), page.getTotal(), page
                .getResult());
    }
}
pay attention
- 爆红的pom.xml
<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
					<encoding>UTF-8</encoding>
					<verbose>false</verbose>
				</configuration>
			</plugin>
<plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.5.2</version>
            </plugin>
- 实现可选参数(可选参数有可能为null)
 代码实现:(以comment为例)
@GetMapping("/comments")
    @ResponseBody
    public Paging<CommentDO> getAll(@RequestParam(name = "pageNum",required = false) Integer pageNum ,
                                    @RequestParam(name = "pageSize",required = false) Integer pageSize) {
        // 如果 pageNum 或 pageSize 为 null,设置默认值
        int currentPageNum = (pageNum != null) ? pageNum : 1; // 默认页数为 1
        int currentPageSize = (pageSize != null) ? pageSize : 15; // 默认每页 15 条记录
        // 设置当前页数为1,以及每页3条记录
        Page<CommentDO> page = PageHelper.startPage(currentPageNum, currentPageSize).doSelectPage(() -> commentDAO.findAll());
        return new Paging<>(page.getPageNum(), page.getPageSize(), page.getPages(), page.getTotal(), page.getResult());
    }
- 附上Paging POJO类的代码
package com.double.comment.model;
import java.io.Serializable;
import java.util.List;
/**
 * 分页模型
 */
public class Paging<R> implements Serializable {
    private static final long serialVersionUID = 522660448543880825L;
    /**
     * 页数
     */
    private int pageNum = 1;
    /**
     * 每页数量
     */
    private int pageSize = 15;
    /**
     * 总页数
     */
    private int totalPage;
    /**
     * 总记录数
     */
    private long totalCount;
    /**
     * 集合数据
     */
    private List<R> data;
    public Paging() {
    }
    public Paging(int pageNum, int pageSize, int totalPage, long totalCount, List<R> data) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.totalPage = totalPage;
        this.totalCount = totalCount;
        this.data = data;
    }
    public int getPageNum() {
        return pageNum;
    }
    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }
    public int getPageSize() {
        return pageSize;
    }
    public Paging setPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }
    public int getTotalPage() {
        return totalPage;
    }
    public Paging setTotalPage(int totalPage) {
        this.totalPage = totalPage;
        return this;
    }
    public long getTotalCount() {
        return totalCount;
    }
    public Paging setTotalCount(long totalCount) {
        this.totalCount = totalCount;
        return this;
    }
    public List<R> getData() {
        return data;
    }
    public Paging setData(List<R> data) {
        this.data = data;
        return this;
    }
}

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号