PageHelper
If you are using MyBatis, it is recommended to try this pagination plugin. This must be the MOST CONVENIENT pagination plugin !

在springboot中使用PageHelper插件有两种较为相似的方式,一种是配置类,另外一种是配置application,本文要介绍的是配置application文件的方式。方法很简单,分为两步,第一 导入依赖;第二 配置文件。

  • 参考官网:https://github/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

步骤一 导入依赖

在Maven中搜索:pageHelper,选择PageHelper Spring Boot Starter

<!-- https://mvnrepository/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.12</version>
</dependency>

配置application.yaml

  • 使用yaml
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

  • 使用properties
#pagehelper分页插件配置
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

如何使用?

  • 编写接口:
    这个接口依赖一个获取List集合的方法(getUsers),因此在使用PageHelper分页之前,请实现它。
//分页查询
public PageInfo<User> bookPageInfo(int pageNum, int pageSize) {
    PageHelper.startPage(pageNum, pageSize);
    List<User> users = userMapper.getUsers();
    PageInfo<User> PageInfo = new PageInfo<User>(users);
    return PageInfo;
}

常用属性

  • pageNum:当前为第几页

  • pageSize:每页的数据行数

  • startRow:当前页数据从第几条开始

  • endRow:当前页数据从第几条结束

  • pages:总页数

  • prePage:上一页页数

  • nextPage:下一页页数

  • hasPreviousPage:是否有上一页

  • hasNextPage:是否有下一页

  • navigatepageNums:所有页码的数组

测试接口

  • 测试程序
 @Test
 void getPageInfo() {
     PageInfo<User> pageInfo = userService.getPageInfo(1, 3);
     pageInfo.getList().forEach(user -> System.out.println(user));
 }
  • 数据库信息

  • 测试结果

User(username=admin, pass=888888)
User(username=de, pass=88888)
User(username=liming, pass=345678)

更多推荐

PageHelper使用——Spring Boot Starter