MENU

关于Mybatis-Plus框架分页不生效问题解决

May 19, 2025 • Read: 58 • Java,学习

AI 摘要

正在加载摘要...

最近在使用Mybatis-Plus的分页查询方法时候,发现并没有生效。查询的参数为

{
    "current": 1,
    "pageSize":"2"
}

但是实际把所有数据都返回了

{
  "code": 0,
  "data": {
    "records": [
      {
        "id": 1923634783594762241,
        "userAccount": "admin",
        "createTime": "2025-05-17T07:00:46.000+00:00"
      },
      ...
    ],
    "total": 0,
    "size": 2,
    "current": 1,
    "pages": 0
  },
  "message": "ok"
}

这里可以看到返回的 VO 中石油total size等字段的,但是没有生效,于是就去官网看文档,

于 v3.5.9 起,PaginationInnerInterceptor 已分离出来。如需使用,则需单独引入 mybatis-plus-jsqlparser 依赖 , 具体请查看 安装 一章。

解决办法

Maven bom标题下,可以看到

使用 maven bom 管理依赖,减少版本号的冲突。因为 jsqlparser 5.0+ 版本不再支持 jdk8 针对这个问题解耦 jsqlparser 依赖。 正确打开姿势,引入 mybatis-plus-bom 模块,然后引入 ..starter 和 ..jsqlparser.. 依赖

所以需要引入对应的包管理器和依赖

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-bom</artifactId>
            <version>3.5.9+ 版本</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Spring Boot3

<!-- spring boot3 引入可选模块 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency>

Spring Boot2

<!-- spring boot2 引入可选模块 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>

另外还需根据自己JDK版本引入不同的依赖

<!-- jdk 8+ 引入可选模块 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-jsqlparser-4.9</artifactId>
</dependency>
<!-- jdk 11+ 引入可选模块 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-jsqlparser</artifactId>
</dependency>

此外,还需要在 Spring Boot 项目中,通过 Java 配置来添加分页插件

@Configuration
@MapperScan("scan.your.mapper.package")
public class MybatisPlusConfig {

    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
        // 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
        return interceptor;
    }
}

大功告成

{
  "code": 0,
  "data": {
    "records": [
      {
        "id": 1923634783594762241,
        "userAccount": "admin",
        "userRole": "admin",
        "createTime": "2025-05-17T07:00:46.000+00:00"
      },
      {
        "id": 1924441288589975553,
        "userAccount": "test001",
        "userRole": "user",
        "createTime": "2025-05-19T12:25:32.000+00:00"
      }
    ],
    "total": 10,
    "size": 2,
    "current": 1,
    "pages": 5
  },
  "message": "ok"
}
Last Modified: June 1, 2025