同时使用mybatis-plus 和 pagehelper 的分页插件导致 分页失效问题,解决!

  • 作者: 凯哥Java(公众号:凯哥Java)
  • 经验分享
  • 时间:2023-12-07 15:31
  • 1119人已阅读
简介 前言:目前在java的项目中,使用的主流的方式就是一个基于mybatis-plus的.page()的分页,当然这种分页方式是适用于一些简单的查询和简单场景(不想写sql)下。对于多表联查等场景,还是需要通过手写sql来实现复杂查询。那么这个时候又想要有工具帮助我们自动分页,这时候就可以使用pageHelper的分页插件。1.问题描述:在同时使用mybatis-plus和pageHelper时,分页

🔔🔔好消息!好消息!🔔🔔

 如果您需要注册ChatGPT,想要升级ChatGPT4。凯哥可以代注册ChatGPT账号代升级ChatGPT4

有需要的朋友👉:微信号 kaigejava2022

前言:目前在java的项目中,使用的主流的方式就是一个基于mybatis-plus的.page()的分页,当然这种分页方式是适用于一些简单的查询和简单场景(不想写sql)下。对于多表联查等场景,还是需要通过手写sql来实现复杂查询。那么这个时候又想要有工具帮助我们自动分页,这时候就可以使用pageHelper的 分页插件。

1. 问题描述:在同时使用mybatis-plus和pageHelper时,分页失效。

首先我的项目中引入的相关依赖如下:

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.0</version>
</dependency>


首先这两个工具的版本上其实不会存在什么依赖冲突问题。但是分页的时候失效。

2. 不废话 直接上解决方法:添加一个相关配置类,
@Configuration
public class MybatisPlusConfiguration {
 
 
    /**
     * pageHelper分页插件&&mybatisPlus分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
 
    @Bean
    public PaginationInnerInterceptor paginationInterceptor() {
        return new PaginationInnerInterceptor();
    }
 
    @Bean
    PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptor = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("helperDialect", "mysql");
        pageInterceptor.setProperties(properties);
        return pageInterceptor;
    }
}

那么加上这一配置类之后,mybatis-plus的分页和pageHelper的分页就都会会生效了。需要注意的是由于两者都需要用到page,需要在使用的时候区分使用的page是哪个下面的。


例如:使用mybatis-plus的分页时,确保page是com.baomidou.mybatisplus.extension.plugins.pagination下的,


在使用pageHelper的时候确保page是在


com.github.pagehelper

TopTop