插件是独立于Mybatis框架之外的第三方插件
添加分页插件的依赖
在 pom.xml
文件中添加
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
配置插件
在 mybatis
的主配置文件 mybatis-config.xml
中通过 plugins
标签进行配置
<!-- plugins 配置myBatis插件 -->
<plugins>
<!-- 分页插件拦截器 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
分页实例
测试类
@Test
public void queryStudentListByPluginPage() {
StudentDao studentDao = MyBatisUtil.getMapper(StudentDao.class); //sqlSession
// 在sql查询之前先设置分页信息,分页信息设置给sqlSession
// 设置之后,也就创建好了一个pageHelper的拦截器
PageHelper.startPage(2,4);
// mybatis在操作的时候就会检查有没有拦截器,
// 若有,在查询的时候就会把对应的分页信息设置到List<Student>中
List<Student> students = studentDao.queryStudentList();
// 通过new PageInfo 方法,获取和分页有关的信息值
PageInfo<Student> pageInfo = new PageInfo(students);
List<Student> list = pageInfo.getList();
for (Student student : list) {
System.out.println(student);
}
}