赞
踩
https://pagehelper.github.io/docs/howtouse/
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.2</version>
</dependency>
@Configuration
public class AppConfig {
@Bean
public PageInterceptor pageInterceptor() {
PageInterceptor pageInterceptor = new PageInterceptor();
Properties properties = new Properties();
// 分页合理化,true开启,如果分页参数不合理会自动修正。默认false不启用
properties.setProperty("reasonable", "true");
pageInterceptor.setProperties(properties);
return pageInterceptor;
}
}
[Ref] 整合PageHelper实现分页
前提:业务提供 查询所有学生的方法
// com.zhangziwa.practisesvr.mapper.UserMapper#listStudents
<select id="listStudents" resultMap="StudentMap">
SELECT * FROM students
</select>
// com.zhangziwa.practisesvr.mapper.UserMapper
List<Student> listStudents();
不使用分页插件 会查出全部
List<Student> students = userMapper.listStudents();
分页查询 方式1:PageInfo
public List<Student> listStudents2(Integer pageNum, Integer PageSize) {
PageHelper.startPage(1, 10, true);
PageHelper.orderBy("age asc");
List<Student> students = userMapper.listStudents();
PageInfo<Student> studentPageInfo = PageInfo.of(students);
return students;
}
分页查询方式2:Page
public List<Student> listStudents2(Integer pageNum, Integer PageSize) {
PageHelper.startPage(1, 10, true);
PageHelper.orderBy("age asc");
Page<Student> students = (Page<Student>) userMapper.listStudents();
return students;
}
分页查询方式3:多数据源聚合时的手工分页
public List<Student> listStudents3(Integer pageNum, Integer pageSize) {
// 模拟数据聚合
List<Student> students3 = new ArrayList<>();
List<Student> students1 = userMapper.listStudents();
List<Student> students2 = userMapper.listStudents();
students3.addAll(students1);
students3.addAll(students2);
Page<Student> studentsPage = PageHeaderUtils.manualPage(students3, pageNum, pageSize);
return studentsPage;
}
// 数据聚合场景下的手工分页 // 也适合EmptyList场景 Page{count=true, pageNum=1, pageSize=10, startRow=0, endRow=0, total=0, pages=0, reasonable=null, pageSizeZero=null} public static <E> Page<E> manualPage(List<E> res, Integer pageNum, Integer pageSize) { if (res == null) { res = new ArrayList<>(); } int pageNumber = PageUtils.getPageNum(pageNum); int sizePerPage = PageUtils.getPageSize(pageSize); int totalSize = res.size(); List<E> pageElements = res.stream().skip((long) (pageNumber - 1) * sizePerPage).limit(sizePerPage).toList(); // 分页 Page<E> page = new Page<>(); page.setPageNum(pageNumber); page.setPageSize(sizePerPage); page.setTotal(totalSize); page.setPages((totalSize / pageSize + ((totalSize % pageSize == 0) ? 0 : 1))); page.addAll(pageElements); return page; }
[Q&A] 在系统中发现了多个分页插件
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。