当前位置: 首页 > news >正文

Springboot 自定义mybatis 拦截器,实现我们要的扩展

前言

相信大家对拦截器并不陌生,对mybatis也不陌生。

有用过pagehelper的,那么对mybatis拦截器也不陌生了,按照使用的规则触发sql拦截,帮我们自动添加分页参数 。

那么今天,我们的实践 自定义mybatis拦截器也是如此, 本篇文章实践的效果:


针对一些使用 单个实体类去接收返回结果的 mapper方法,我们拦截检测,如果没写 LIMIT 1 ,我们将自动帮忙填充,达到查找单条数据 效率优化的效果。

ps: 当然,跟着该篇学会了这个之后,那么可以扩展的东西就多了,大家按照自己的想法或是项目需求都可以自己发挥。 我该篇的实践仅仅作为抛砖引玉吧。

正文

实践的准备 :
 

整合mybatis ,然后故意写了3个查询方法, 1个是list 列表数据,2个是 单条数据 。

我们通过自己写一个MybatisInterceptor实现 mybatis框架的 Interceptor来做文章:
 

MybatisInterceptor.java :

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.*;



/**
 * @Author JCccc
 * @Description
 * @Date 2021/12/14 16:56
 */
@Component
@Intercepts({

        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //获取执行参数
        Object[] objects = invocation.getArgs();
        MappedStatement ms = (MappedStatement) objects[0];
        //解析执行sql的map方法,开始自定义规则匹配逻辑
        String mapperMethodAllName = ms.getId();
        int lastIndex = mapperMethodAllName.lastIndexOf(".");
        String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);
        String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));
        Class<?> mapperClass = Class.forName(mapperClassStr);
        Method[] methods = mapperClass.getMethods();
        Class<?> returnType;
        for (Method method : methods) {
            if (method.getName().equals(mapperClassMethodStr)) {
                returnType = method.getReturnType();
                if (returnType.isAssignableFrom(List.class)) {
                    System.out.println("返回类型是 List");
                    System.out.println("针对List 做一些操作");
                } else if (returnType.isAssignableFrom(Set.class)) {
                    System.out.println("返回类型是 Set");
                    System.out.println("针对Set 做一些操作");
                } else{
                    BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
                    String oldSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");
                    if (!oldSql.contains("LIMIT")){
                        String newSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ") + " LIMIT 1";
                        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
                                boundSql.getParameterMappings(), boundSql.getParameterObject());
                        MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(newBoundSql));
                        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
                            String prop = mapping.getProperty();
                            if (boundSql.hasAdditionalParameter(prop)) {
                                newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
                            }
                        }
                        Object[] queryArgs = invocation.getArgs();
                        queryArgs[0] = newMs;
                        System.out.println("打印新SQL语句" + newSql);
                    }

                }
            }
        }
        //继续执行逻辑
        return invocation.proceed();
    }


    @Override
    public Object plugin(Object o) {
        //获取代理权
        if (o instanceof Executor) {
            //如果是Executor(执行增删改查操作),则拦截下来
            return Plugin.wrap(o, this);
        } else {
            return o;
        }
    }

    /**
     * 定义一个内部辅助类,作用是包装 SQL
     */
    class MyBoundSqlSqlSource implements SqlSource {
        private BoundSql boundSql;

        public MyBoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        @Override
        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }

    }

    private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new
                MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }


    @Override
    public void setProperties(Properties properties) {
        //读取mybatis配置文件中属性
    }


}

简单代码端解析:

① 拿出执行参数,里面有很多东西给我们用的,我本篇主要是用MappedStatement。大家可以发挥自己的想法。 打debug可以自己看看里面的东西。

//获取执行参数
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];

 

 ② 这里我主要是使用了从MappedStatement里面拿出来的id,做切割分别切出来 目前执行的sql的mapper是哪个,然后方法是哪个。

String mapperMethodAllName = ms.getId();
int lastIndex = mapperMethodAllName.lastIndexOf(".");
String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);
String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));

③ 这就是我自己随便写的一下,我直接根据切割出来的mapper类找出里面的方法,主要是为了拿出每个方法的返回类型,因为 我这篇实践内容就是,判断出单个pojo接受的mapper方法,加个LIMIT 1 , 其他的 LIST 、SET 、 Page 等等这些,我暂时不做扩展。

Class<?> mapperClass = Class.forName(mapperClassStr);
Method[] methods = mapperClass.getMethods();
Class<?> returnType;

 ④这一段代码就是该篇的拓展逻辑了,从MappedStatement里面拿出 SqlSource,然后再拿出BoundSql,然后一顿操作 给加上 LIMIT 1  , 然后new 一个新的 MappedStatement,一顿操作塞回去invocation 里面。

BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String oldSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");
if (!oldSql.contains("LIMIT")){
    String newSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ") + " LIMIT 1";
    BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,
            boundSql.getParameterMappings(), boundSql.getParameterObject());
    MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(newBoundSql));
    for (ParameterMapping mapping : boundSql.getParameterMappings()) {
        String prop = mapping.getProperty();
        if (boundSql.hasAdditionalParameter(prop)) {
            newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
        }
    }
    Object[] queryArgs = invocation.getArgs();
    queryArgs[0] = newMs;
    System.out.println("打印新SQL语句:" + newSql);
}

OK,最后简单来试试效果 :
 

 

最后再重申一下,本篇文章内容只是一个抛砖引玉,随便想的一些实践效果,大家可以按照自己的想法发挥。

最后再补充一个 解决 mybatis自定义拦截器和 pagehelper 拦截器 冲突导致失效的问题出现的 解决方案:

加上一个拦截器配置类 


MyDataSourceInterceptorConfig.java :

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author JCccc
 * @Description
 * @Date 2021/12/14 16:56
 */
@Component
public class MyDataSourceInterceptorConfig implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private MybatisInterceptor mybatisInterceptor;

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactories;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        for (SqlSessionFactory factory : sqlSessionFactories) {
            factory.getConfiguration().addInterceptor(mybatisInterceptor);
        }
    }
}

最后最后再补充多一些,

文中 针对拦截的是Executor 这种接口的插件,

其实 还可以使用ParameterHandler、ResultSetHandler、StatementHandler。

每当执行这四种接口对象的方法时,就会进入拦截方法,然后我们可以根据不同的插件去拿不同的参数。

类似:

@Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class,Integer.class})

然后可以做个转换,也是可以取出相关的 BoundSql 等等 :

if (!(invocation.getTarget() instanceof RoutingStatementHandler)){
                return invocation.proceed();
            }
            RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
            BoundSql boundSql = statementHandler.getBoundSql();
            String sql = boundSql.getSql().toUpperCase();

ParameterHandler、ResultSetHandler、StatementHandler、Executor ,不同的插件拦截,有不同的使用场景,想深入的看客们,可以深一下。

相关文章:

  • Eureka 一直刷 Running the evict task with compensationTime 0ms
  • Eureka 注册、下线、续约事件的监听使用
  • Java Thread.sleep(),结合例子只学一次
  • Java ArrayList new出来,默认的容量到底是0还是10 ?
  • Mysql 关于 int(1) 和 int(11) , 我必须要说一下了。
  • SpringCloud 整合注册中心,配置中心 Nacos (九)
  • Springboot 自定义注解AOP实现时间参数格式转换
  • 看什么看啊,你不会还不会抓HTTPS请求报文吧?
  • 做一个合格的开发,从玩转Apipost开始
  • Springboot 整合 企业微信机器人助手推送消息
  • Springboot 同一次调用日志怎么用ID串起来,方便最终查找
  • IDEA 运行Tomcat项目 控制台乱码
  • Springboot 整合 xxljob 使用定时任务调度(新手入门篇)
  • Springboot @SpringBootTest 单元测试执行两次的问题
  • Amazon ElastiCache 飞速搭建缓存服务集群,这才叫快
  • (三)从jvm层面了解线程的启动和停止
  • [译]如何构建服务器端web组件,为何要构建?
  • 4. 路由到控制器 - Laravel从零开始教程
  • Angular 响应式表单 基础例子
  • Apache的80端口被占用以及访问时报错403
  • C++回声服务器_9-epoll边缘触发模式版本服务器
  • CentOS6 编译安装 redis-3.2.3
  • httpie使用详解
  • JAVA之继承和多态
  • nginx 配置多 域名 + 多 https
  • supervisor 永不挂掉的进程 安装以及使用
  • tensorflow学习笔记3——MNIST应用篇
  • 从输入URL到页面加载发生了什么
  • 回流、重绘及其优化
  • 简单基于spring的redis配置(单机和集群模式)
  • 京东美团研发面经
  • 开放才能进步!Angular和Wijmo一起走过的日子
  • 前端
  • 树莓派 - 使用须知
  • 我与Jetbrains的这些年
  • 译自由幺半群
  • 源码安装memcached和php memcache扩展
  • ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException
  • #define,static,const,三种常量的区别
  • ( 用例图)定义了系统的功能需求,它是从系统的外部看系统功能,并不描述系统内部对功能的具体实现
  • (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!
  • (附程序)AD采集中的10种经典软件滤波程序优缺点分析
  • (附源码)小程序 交通违法举报系统 毕业设计 242045
  • (黑马C++)L06 重载与继承
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (算法)求1到1亿间的质数或素数
  • (五)MySQL的备份及恢复
  • (转)IOS中获取各种文件的目录路径的方法
  • (转)负载均衡,回话保持,cookie
  • (转)项目管理杂谈-我所期望的新人
  • .NET CF命令行调试器MDbg入门(二) 设备模拟器
  • .net wcf memory gates checking failed
  • .NET 除了用 Task 之外,如何自己写一个可以 await 的对象?
  • .net打印*三角形