===============
MyBatis分页插件
===============
分页插件PageHelper是一个独立于MyBatis框架之外的第三方插件。
在pom.xml文件中添加依赖:
com.github.pagehelper
pagehelper
5.1.10
在mybatis-config.xml中配置插件:
分页查询:
public class StudentDaoTest {
...
// 测试基于插件的分页查询
@Test
public void testPagByPlugin() {
// 数据访问对象
StudentDao dao = MyBatisUtil.getMapper(StudentDao.class);
// 分页查询
PageHelper.startPage(1, 2); // 设置拦截器
List page = dao.all(); // 一页记录
PageInfo pageInfo = new PageInfo<>(page); // 包含页码等更多信息
List students = pageInfo.getList(); // 获取一页记录
// 打印分页
for (Student student : students)
System.out.println(student);
}
...
}
分页查询特定性别:
public interface StudentDao {
...
// 根据性别查询
public List allOfGender(String gender);
...
}
...
...
public class StudentDaoTest {
...
// 测试根据性别查询
@Test
public void testAllOfGender() {
// 数据访问对象
StudentDao dao = MyBatisUtil.getMapper(StudentDao.class);
// 根据性别分页查询
PageHelper.startPage(1, 2);
List page = dao.allOfGender("女");
PageInfo pageInfo = new PageInfo<>(page);
List students = pageInfo.getList();
// 打印分页
for (Student student : students)
System.out.println(student);
}
...
}
例程:HelloMyBatis