https://github.com/pagehelper/Mybatis-PageHelper

实现步骤

【无Sprin-boot的情况下】

  1. maven坐标

    1. <dependency>
    2. <groupId>com.github.pagehelper</groupId>
    3. <artifactId>pagehelper</artifactId>
    4. <version>5.2.0</version>
    5. </dependency>
  2. 加入plugin配置

plugin标签只能放在 environments前面

  1. <plugins>
  2. <plugin interceptor="com.github.pagehelper.PageInterceptor" />
  3. </plugins>
  4. <environments default="myDev">

或者采用如下配置方法(在spring配置mybatis的文件中)

  1. <!-- 创建mybatis的sqlSessionFactoryBean-->
  2. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  3. <property name="dataSource" ref="dataSource"/>
  4. <property name="configLocation" value="classpath:conf/mybatis-config.xml"/>
  5. <property name="mapperLocations" value="classpath:mybatis/mapper/AdminMapper.xml"/>
  6. <property name="plugins">
  7. <array>
  8. <!-- PageHelper5.0之后使用该方法进行配置插件-->
  9. <bean class="com.github.pagehelper.PageInterceptor">
  10. <property name="properties">
  11. <value>
  12. reasonable=true
  13. </value>
  14. </property>
  15. </bean>
  16. </array>
  17. </property>
  18. </bean>
  1. 在要分页的查询语句之前加上Pagehelper的方法

PageHelper.startPage(pageNum, pageSize)

  • pageNum:第几页
  • pageSize:每页有几项内容
    1. @Test
    2. public void testSelectAllStudents(){
    3. SqlSession sqlSession = MyBatisUtils.getSqlSession();
    4. StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
    5. // PageHelper会将紧随其后的查询结果进行分页处理
    6. PageHelper.startPage(2, 3);
    7. List<Student> res = studentDao.selectAllStudents();
    8. res.forEach(student -> System.out.println(student));
    9. }

结果

  1. 先计算有多少行
  2. ==> Preparing: SELECT count(0) FROM student
  3. ==> Parameters:
  4. <== Columns: count(0)
  5. <== Row: 4
  6. <== Total: 1
  7. ==> Preparing: select id, name, email, age from student LIMIT ?, ?
  8. ==> Parameters: 3(Long), 3(Integer)
  9. <== Columns: id, name, email, age
  10. <== Row: 1005, 张飞, zhangfei@163.com, 20
  11. <== Total: 1