项目使用mybatis-plus分页插件和pageHelper分页插件引起失效问题!

一、背景

项目中以前的源码是使用pageHelper分页插件来实现。涉及到的sql代码还是要手写部分。而目前在Springboot项目中,使用的主流的方式就是一个基于mybatis-plus的.page()的分页,当然这种分页方式是适用于一些简单的查询和简单场景下。对于多表联查等场景,可能还是需要通过手写sql来实现复杂查询。这时候就可以使用pageHelper的 分页插件。

二、 问题描述

在同时使用mybatis-plus和pageHelper时,导致了pageHelper分页失效。
首先我的项目中引入的相关依赖如下:

pageHelper 版本是5.3.2

项目使用mybatis-plus分页插件和pageHelper分页插件引起失效问题!_第1张图片

mybatis-plus的版本是3.4.3

使用maven Helper工具可以查看到,这两个工具的版本上其实会存在sqlparser依赖版本冲突问题。pageHelper引用的是sqlparser4.5版本,mybatis-plus引用的是sqlparser4.0版本,但是也不是导致分页失效的主要原因。

项目使用mybatis-plus分页插件和pageHelper分页插件引起失效问题!_第2张图片

三、解决方案

原来只是配置MyBatisPlus 的MybatisPlusInterceptor 。

@Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

需要增加com.github.pagehelper.PageInterceptor;的配置,直接给完整的配置类代码。


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.github.pagehelper.PageInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Properties;

/**
 *
 */
/***
 * @Author: javinlu
 * @Description: MyBatis plus 相关配置
 * @Date: 2024/11/18 11:35
 **/
@Configuration
@EnableTransactionManagement
@MapperScan({"com.macro.mall.mapper", "com.macro.mall.dao"})
public class MyBatisPlusConfig {
    @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是哪个下面的。别import错了也会导致失效。

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

在使用pageHelper的时候确保page是在 com.github.pagehelper.PageInterceptor。

你可能感兴趣的:(mybatis,java,springboot,个人开发,深度学习)