对于分页插件PageHelper:通常情况下使用在查询前加上,从数据库里查询出来的数据就是已经分页好的了
PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
但是,当我们要对查询到的数据进行进一步操作,然后再进行分页的时候(比如查询出来后的数据,进行计算过滤去重后再分页),数据就不是我们想要的数据了,或者说上面的分页方法会失效了,达不到想要的效果,则我们需要手动进行分页,下面展示手动分页步骤:
//list 需要分页的数据列表 getPageNum() 获取当前页码 ;getPageSize()获取页面显示多少条数
PageInfo pageInfo = new PageInfo(list.isEmpty() ? list.emptyList() : list);
// startPage为下面自定义的方法
pageInfo.setList(list.isEmpty() ? Collections.emptyList() : startPage(list,vo.getPageNum(), vo.getPageSize()));
pageInfo.setPageNum(vo.getPageNum());
pageInfo.setPageSize(vo.getPageSize());
分页所需的依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
可以在自己的工具类里面写上这个分页方法:
public static List startPage(List list, Integer pageNum, Integer pageSize) {
if (list == null) {
return Collections.emptyList();
}
if (list.isEmpty()) {
return Collections.emptyList();
}
//记录总数
Integer count = list.size();
//开始索引
int fromIndex = (pageNum - 1) * pageSize;
//结束索引
int toIndex = pageNum * pageSize;
if (fromIndex + 1 > count) {
return Collections.emptyList();
}
if (pageNum * pageSize > count) {
toIndex = count;
}
return list.subList(fromIndex, toIndex);
}