1.maven中加入pageHelper依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency>
2.Mybatis配置文件中添加分页插件
<plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- config params as the following --> <!--<!–分页参数合理化 –>--> <property name="reasonable" value="true"/> </plugin> </plugins>
reasonable的配置:
reasonable:分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页,pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根据参数进行查询。
3.代码实现
@Test public void selectAll(){ SqlSession session = sessionFactory.openSession(); InsertUser insertUser = session.getMapper(InsertUser.class); PageHelper.startPage(2, 3); // List<UserEntity> list = insertUser.selectAll(); PageInfo<UserEntity> info = new PageInfo<UserEntity>(list);
System.out.println("总记录数"+info.getTotal()); System.out.println("总页数"+info.getPages()); System.out.println("每页条数"+info.getPageSize()); System.out.println("当前页"+info.getPageNum()); System.out.println("上一页"+info.getPrePage()); System.out.println("下一页"+info.getNextPage()); for (UserEntity userEntity : list) { System.out.println(userEntity); } session.close(); }