什么是PageHelper插件?
PageHelper是适用于MyBatis框架的一个分页插件,使用方式极为便捷,支持任何复杂的单表、多表分页查询操作。
下载地址:GitHub - pagehelper/Mybatis-PageHelper: Mybatis通用分页插件
配置环境
首先在pom.xml文件中导入该插件的依赖包
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency
在MyBatis配置文件中加入插件
<!-- 在mybatis配置中加入插件 -->
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
示例
StudentDao studentDao = MyBatisUtils.getMapper(StudentDao.class);
PageHelper.startPage(1,5);
List<Student> students = studentDao.selectAll();
PageInfo page=new PageInfo(students);
System.out.println("首页:"+page.getNavigateFirstPage());
System.out.println("尾页:"+page.getNavigateLastPage());
System.out.println("当前页:"+page.getPageNum());
System.out.println("页数量:"+page.getPages());
特别注意:
-
只有在PageHelper.startPage()方法之后的第一个查询会有执行分页。
-
分页插件不支持带有“for update”的查询语句。(for update: 行级锁)
-
分页插件不支持“嵌套查询”; (嵌套查询:两张表的查询有嵌套关系)