MyBatis的分页查询需要手动实现,MyBatis并没有提供现成的分页功能。接下来跟着本文章来一步一步实现它。
1.需求明确
首先要明确分页查询SQL语句怎么写:
SELECT * FROM `user` LIMIT startIndex,count
startIndex:指定从第哪一条条记录开始查询(不包含当前记录,即实际是从startIndex+1开始的)
count: 指定查询多少条数据
- count是人为指定的,即需要一页显示多少条数据。
- startIndex是程序计算出来的,取决于当前查询的页数和每页的记录数。计算方式是:(当前要查询的页码-1)* 每页要查询的记录数。
此外,还需要得到总记录数,总页数。这些可能都是需要在前端显示的。
2.编写Page类
新建page包并在包下新创建Page类,代码如下:
package com.yky.springboot.page;
import java.util.List;
public class Page<T> {
//每页显示的记录数
private int lineSize = 5;
//总记录数
private long totalRecord;
//用户指定的页数
private int currentPage;
//起始位置
private long startIndex;
//总页数
int pageCount;
List<T> list;
public Page(int currentPage, long totalRecord, int lineSize) {
this.currentPage = currentPage;
this.totalRecord = totalRecord;
this.lineSize = lineSize;
//计算出pageCount
this.pageCount = (int) ((totalRecord % lineSize) != 0 ? ((totalRecord / lineSize) + 1) : (totalRecord / lineSize));
//计算出起始位置,注意,从0下标开始
this.startIndex = (currentPage - 1) * lineSize;
}
public long getStartIndex() {
return (currentPage - 1) * lineSize;
}
public void setStartIndex(long startIndex) {
this.startIndex = startIndex;
}
public int getLineSize() {
return lineSize;
}
public void setLineSize(int lineSize) {
this.lineSize = lineSize;
}
public long getTotalRecord()