11、分页插件
分页插件PageHelper在MyBatis中的使用:
11.1、引入配置
1、引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
2、在核心配置文件中加入配置
<plugins>
<!--设置分页插件-->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
11.2、使用
1、PageHelper.startPage(PageNumber, PageSize);
执行查询之前,先设置要查询的分页,以及页面大小。
@Test
public void test() throws Exception {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = factoryBuilder.build(is);
SqlSession sqlSession = factory.openSession(true);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
PageHelper.startPage(1, 5);
List<Student> students = mapper.selectAll();
students.forEach(student ->{
System.out.println(student);
});
}
2、PageInfo
可以利用PageInfo获取更多分页信息,便于前端使用
@Test
public void test() throws Exception {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = factoryBuilder.build(is);
SqlSession sqlSession = factory.openSession(true);
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
PageHelper.startPage(1, 5);
List<Student> students = mapper.selectAll();
PageInfo<Student> pageInfo = new PageInfo<>(students,5);
System.out.println(pageInfo);
}
输出结果:
PageInfo{
pageNum=1, //当前页数
pageSize=5, //页面大小
size=5, //底部导航跳转标签数
startRow=1, //查询结果起始索引
endRow=5, //查询结果结束索引
total=13, //数据总量
pages=3, //总页面数
list=Page{count=true, pageNum=1, pageSize=5, startRow=0, endRow=5, total=13, pages=3, reasonable=false, pageSizeZero=false}[Student{sId=1, sName='张三', sAge=20, sSex='男', sEmail='123@qq.com', sClass=1}, Student{sId=2, sName='李四', sAge=20, sSex='男', sEmail='123@qq.com', sClass=2}, Student{sId=3, sName='王五', sAge=20, sSex='男', sEmail='123@qq.com', sClass=3}, Student{sId=4, sName='赵六', sAge=20, sSex='男', sEmail='123@qq.com', sClass=1}, Student{sId=5, sName='测试1', sAge=20, sSex='男', sEmail='123@qq.com', sClass=2}], prePage=0, nextPage=2, isFirstPage=true, isLastPage=false, hasPreviousPage=false, hasNextPage=true, navigatePages=5, navigateFirstPage=1, navigateLastPage=3, navigatepageNums=[1, 2, 3]}
//page对象