Skip to content

在Spring Boot中使用PageHelper插件

PageHelper是用于MyBatis的分页插件,本文主要介绍了如何在Spring Boot中使用PageHelper。

官方地址: https://pagehelper.github.io/

pagehelper-spring-boot: https://github.com/pagehelper/pagehelper-spring-boot

1. 引入依赖

在pom.xml文件中引入以下依赖:

xml
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>${pagehelper-version}</version>
</dependency>

2. 编写查询语句

java
@Mapper
public interface StudentMapper {

    List<Student> queryStudent(@Param("pageNum")int pageNum, @Param("pageSize") int pageSize);

}
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.example.springbootdemo.mapper.StudentMapper">
    <select id="queryStudent" resultType="org.example.springbootdemo.entity.po.Student">
        select * from student
    </select>
</mapper>

注意:分页查询的默认名字是pageNumpageSize。我们不用在查询语句中手动处理。

3. 返回分页信息

编写测试类:

java
]@SpringBootTest
public class StudentMapperTest {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private ObjectMapper objectMapper;

    @Test
    void test01() throws JsonProcessingException {
        List<Student> students = studentMapper.queryStudent(1,2);
        PageInfo pageInfo = new PageInfo(students);
        String json = objectMapper.writeValueAsString(pageInfo);
        System.out.println(json);
    }
}

我们可以将返回值用PageInfo进行包装得到完整的分页信息:

json
{
    "total": 6,
    "list": [
        {
            "id": 1,
            "name": "张三",
            "birthday": "2000-01-01",
            "address": "广州"
        },
        {
            "id": 2,
            "name": "李四",
            "birthday": "1999-12-01",
            "address": "上海"
        }
    ],
    "pageNum": 1,
    "pageSize": 2,
    "size": 2,
    "startRow": 1,
    "endRow": 2,
    "pages": 3,
    "prePage": 0,
    "nextPage": 2,
    "isFirstPage": true,
    "isLastPage": false,
    "hasPreviousPage": false,
    "hasNextPage": true,
    "navigatePages": 8,
    "navigatepageNums": [
        1,
        2,
        3
    ],
    "navigateFirstPage": 1,
    "navigateLastPage": 3
}

4. 配置PageHelper

我们可以在application.yml中配置PageHelper:

yaml
pagehelper:
  reasonable: true
  support-methods-arguments: true
  • reasonable:分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根据参数进行查询。
  • supportMethodsArguments:支持通过 Mapper 接口参数来传递分页参数,默认值false,分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,查找到合适的值时就会自动分页。 使用方法可以参考测试代码中的 com.github.pagehelper.test.basic 包下的 ArgumentsMapTestArgumentsObjTest

完整的配置表参照官网信息:https://pagehelper.github.io/docs/howtouse/#2-配置拦截器插件