关于mybatis-plus分页不生效

前言:

最近公司又重启了以前的一个项目,写分页的时候发现居然不生效,用的是mybatisplus(以下简称mp)的分页。


问题描述

mp也是我前端时间集成进去的了,只是最近又要追加需求,结果在写查询接口的时候就发现分页不管用,如图:

请求完成示意图
这是debug之后,返回体的情况,我表中一共12条数据,我测试的分页是第一页,条数是5。结果返回的列表还是12条,总数直接显示的0。只有页数和条数对了,这两个属性当然是对的,因为这个Page是我塞入这两个属性创建的。

根据以往的经验,我猜测是忘了加mp的分页拦截器。于是找到官网,准备添加如下代码:

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

结果打开配置类才发现,当时我集成mp的时候,已经把这块拦截器写上了。。。它就是没生效!


原因分析:

那么我首先就去查一下为什么不生效,我第一反应是拦截器拼接sql有问题。是不是没获取到分页,然后我找到mp的分页拦截器PaginationInnerInterceptor中的beforeQuery,然后打了个断点,打算看一下分页参数有没有异常。
分页拦截器断点
结果我测了好几次,居然一次都没进来。于是我找到mp的总拦截器MybatisPlusInterceptorintercept方法,准备看一下分页拦截器是啥情况。结果,这个拦截器都没进入。
在这里插入图片描述
这下我大概明白了,拦截器有点问题,看了一下依赖,发现居然用了pagehelper。然后找到了它的拦截器PageInterceptor,找到了intercept方法,打了个断点。
在这里插入图片描述
果然是这样,它走了pagehelper的拦截器,没有走mp的。


解决方案:

既然知道了原因,那就很简单了。mp的分页是一个插件,只需要将这个插件放到sqlSessionFactory中即可。
在这里插入图片描述

@Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
    {
        String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage");
        String mapperLocations = env.getProperty("mybatis.mapperLocations");
        String configLocation = env.getProperty("mybatis.configLocation");
        typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
        VFS.addImplClass(SpringBootVFS.class);

        final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean ();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
        sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ",")));
        sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
        sessionFactory.setPlugins(mybatisPlusInterceptor());
        return sessionFactory.getObject();
    }
    /**
     * 添加分页插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//如果配置多个插件,切记分页最后添加
        //interceptor.addInnerInterceptor(new PaginationInnerInterceptor()); 如果有多数据源可以不配具体类型 否则都建议配上具体的DbType
        return interceptor;
    }

至于其他配置“typeAliasesPackage ”,“mapperLocations ”什么的,是的,没错,那是若依框架的。
至此,成功解决问题。
在这里插入图片描述