SpringBoot项目实战(005)mybatis拦截器实现分页

说明

之前使用了com.github.pagehelper.pagehelper实现分页,现在参考源代码,自己简单实现一下功能。
插件源码地址:https://github.com/pagehelper/Mybatis-PageHelper

基础代码

基础代码可以参考:《SpringBoot项目实战(001)mybatis通过xml实现mapper》

主要代码说明

  • DataSourceConfig:数据源配置,可以配置mybatis的拦截器
  • PageInfo;用于传入分页参数
  • Dialect;方言,针对不同数据库,实现不同的方言,本文使用mysql
  • MybatisInterceptor;mybatis拦截器,实现分页功能

第一步,安装拦截器

首先把拦截器创建出来,并在mybatis的config中,使用拦截器。

简单修改DataSourceConfig.java

    // mybatis配置
    private org.apache.ibatis.session.Configuration createMybatisConfig() {
    
    
        ......
        // 加入拦截器
        config.addInterceptor(getMybatisIntercepts());
        return config;
    }
    private Interceptor getMybatisIntercepts() {
    
    
        Interceptor interceptor = new MybatisInterceptor();
        return interceptor;
    }

MybatisInterceptor.java代码,基本上是空的

package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * MybatisInterceptor
 */
@Intercepts({
    
    
    @Signature(type = Executor.class, method = "query", args = {
    
     MappedStatement.class, Object.class, RowBounds.class,
            ResultHandler.class }),
    @Signature(type = Executor.class, method = "query", args = {
    
     MappedStatement.class, Object.class, RowBounds.class,
            ResultHandler.class, CacheKey.class, BoundSql.class }), })
public class MybatisInterceptor implements Interceptor {
    
    
    private volatile IDialect dialect;

    public Object intercept(Invocation invocation) throws Throwable {
    
    
        try {
    
    
            Object[] args = invocation.getArgs();
            return null;
        } finally {
    
    
            if (dialect != null) {
    
    
                dialect.afterAll();
            }
        }
    }

    public Object plugin(Object target) {
    
    
        return Plugin.wrap(target, this);
    }
}

IDialect.java

package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.RowBounds;
public interface IDialect {
    
    
    void afterAll();
    String getPagedSql(BoundSql boundSql,RowBounds rowBounds);
}

断点打在MybatisInterceptorintercept方法处,运行debug,postman调个GET方法,可得:

在这里插入图片描述

可以看到,有四个参数,仔细看一下,大致功能:

扫描二维码关注公众号,回复: 11753833 查看本文章
  1. mybatis的mapper方面的信息
  2. 参数方面的信息
  3. 分页信息:limit offset
  4. null

那我们需要做的就是找到查询语句,根据dialect改写为分页的语句,返回结果即可。

第二步,调整功能

整理参数,把三个参数包括Executor都整理出来。我们的目的是通过调整sql语句,再使用Executor完成原本的调用。

        // 参数
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        // 执行器
        Executor executor = (Executor) invocation.getTarget();
        // sql
        BoundSql boundSql = ms.getBoundSql(parameter);
        // 分页sql
        String sql = dialect.getPagedSql(boundSql, rb);

新增MySqlDialect,实现功能getPageSql,将BoundSql中的sql调整为分页的。

//实现
package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

public class MySqlDialect implements IDialect {
    
    
    @Override
    public void afterAll() {
    
    
    }

    @Override
    public String getPagedSql(BoundSql boundSql, RowBounds rowBounds) {
    
    
        String sql = boundSql.getSql();
        StringBuilder sb = new StringBuilder();
        sb.append(sql);
        sb.append(" LIMIT ");
        sb.append(rowBounds.getOffset());
        sb.append(",");
        sb.append(rowBounds.getLimit());
        return sb.toString();
    }
}

第三步,输入参数

现在修改整条request链路,所有findall方法增加pageinfo参数。

首先,新增pageinfo类型:

package com.it_laowu.springbootstudy.springbootstudydemo.core.pagehelper;
import lombok.Data;

@Data
public class PageInfo  {
    
    
    // 分页,第几页
    private int pageNum;
    // 分页,每页大小
    private int pageSize;
}

OrderController 修改 orders 方法,增加一个参数

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public List<OrderBean> orders(OrderCondition orderCondition,PageInfo pageinfo) {
    
    
        return orderService.findAll(orderCondition,pageinfo);
    }

IBaseService 修改findall方法,增加pageinfo参数,注意@Param("pageinfo")定义参数的名字

    default List<Bean> findAll(@Param("conditionQC") Condition condition,@Param("pageinfo") PageInfo
     pageinfo){
    
    
        return getBaseDao().findAll(condition,pageinfo);
    }

IBaseDao 修改findall方法,增加pageinfo参数,注意@Param("pageinfo")定义参数的名字

    public List<Bean> findAll(@Param("conditionQC") Condition conditionQC,@Param("pageinfo") PageInfo pageinfo);

第四步,完善拦截器

在拦截器中找到pageinfo参数,如果有分页参数,就将值传给方言进行分页,最后返回数据。
方言可以通过datasource的配置,自动读取,本文直接设置为MysqlDialect。

    public Object intercept(Invocation invocation) throws Throwable {
    
    
        try {
    
    
            Object[] args = invocation.getArgs();
            MappedStatement ms = (MappedStatement) args[0];
            Object parameter = args[1];
            RowBounds rowBounds = (RowBounds) args[2];
            ResultHandler resultHandler = (ResultHandler) args[3];
            Executor executor = (Executor) invocation.getTarget();
            BoundSql boundSql = ms.getBoundSql(parameter);

            ParamMap params = (ParamMap) parameter;
            // 判断参数中是否有分页
            if (params.containsKey("pageinfo")) {
    
    
                PageInfo pageinfo = (PageInfo) params.get("pageinfo");
                if (pageinfo.getPageNum() > 0 && pageinfo.getPageSize() > 0) {
    
    
                    RowBounds rb = new RowBounds((pageinfo.getPageNum() - 1) * pageinfo.getPageSize(),
                            pageinfo.getPageSize());
                    // 使用方言分页
                    String sql = dialect.getPagedSql(boundSql, rb);
                    boundSql = new BoundSql(ms.getConfiguration(), sql, boundSql.getParameterMappings(), parameter);
                    return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, null, boundSql);
                }
            }
            return invocation.proceed();
        } finally {
    
    
            if (dialect != null) {
    
    
                dialect.afterAll();
            }
        }
    }

使用postman测试

list方法,使用分页参数,返回分页结果:

list方法,使用分页参数

list方法,不使用分页参数,返回所有结果:

list方法,不使用分页参数

findOne方法(后台不接受分页参数),可以看到加入分页参数,也不会分页:

findOne方法(后台不接受分页参数),可以看到加入分页参数

猜你喜欢

转载自blog.csdn.net/weixin_36572983/article/details/105600507