配置依赖
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
PS:springboot 2.6以上仅支持 1.4.1以上的版本
在application.yml中添加配置
# 分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
java代码中使用
public PageBean<Staff> getAll(int page, int pageSize) {
Page p = PageHelper.startPage(page, pageSize);
// 根据条件,页码,分页大小,将PageBean中的属性依次设置
PageBean<Staff> pageBean = new PageBean<>();
List<Staff> data = null;
try {
data = staffMapper.findList();
} catch (Exception e) {
e.printStackTrace();
}
pageBean.setData(data);
pageBean.setCurrPage(page);
pageBean.setCurrPageSize(data.size());
pageBean.setPageSize(pageSize);
pageBean.setTotalNums((int) p.getTotal());
pageBean.setTotalPages(p.getPages());
return pageBean;
}
pageBean
@Data
public class PageBean<T> {
private List<T> data; // 当前页数据
private int currPageSize; // 当前页数据的数量
private int currPage; // 当前页面
private int totalPages;// 总页数
private int totalNums;// 总数量
private int pageSize;// 分页大小
}