Mybatis插件原理及集成到springboot

前言

本文介绍的内容如下

  • Mybatis提供的插件(Plugin)机制
  • 基于插件实现一个记录sql语句及耗时的小案例
  • 分析下插件的原理

Plugin

Mybatis提供了四大对象,可供我们使用插件进行扩展,扩展的原理是使用动态代理

  • Executor (update, query, flushStatements, commit, rollback,
    getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

其中Executor类是非常重要的,Mybatis的所有增删改查都会经过query或者update这两个方法,所以我们拦截的主要方法就是query或者update了

也可以在官网查询到:https://mybatis.org/mybatis-3/zh/configuration.html#plugins
在这里插入图片描述

插件源码

我们先从源码开始分析,只介绍Executor的插件

Executor的插件是在创建Executor时使用的,Executor是在创建SqlSession是创建的,所以我们直接从创建SqlSession的地方开始看

DefaultSqlSessionFactory的openSession方法

public SqlSession openSession() {
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
      // 核心代码
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      closeTransaction(tx); // may have fetched a connection so lets call close()
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

继续跟

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    if (ExecutorType.BATCH == executorType) {
      executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
      executor = new ReuseExecutor(this, transaction);
    } else {
      executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    // 核心代码
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

上述核心代码处,interceptorChain就是所有的插件,Mybatis在项目启动时会把所有插件增加到interceptorChain中

public Object pluginAll(Object target) {
    for (Interceptor interceptor : interceptors) {
      // 核心代码
      target = interceptor.plugin(target);
    }
    return target;
  }

核心代码处,调用所有插件的plugin方法,传入了当前Exector对象,返回了另外一个对象,至此插件源码分析完了,也就是说我们的核心逻辑都在我们插件类的plugin方法中了

集成插件时Mybatis提供给我们的一个Interceptor 接口,定义如下

public interface Interceptor {

  Object intercept(Invocation invocation) throws Throwable;

  Object plugin(Object target);

  void setProperties(Properties properties);

}

使用插件

我们参照分页插件PageHelper的源码自己写了一个日志插件,代码如下

@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 LogInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        BoundSql boundSql;
        if (args.length == 4) {
            //4 个参数时
            boundSql = ms.getBoundSql(args[1]);
        } else {
            //6 个参数时
            boundSql = (BoundSql) args[5];
        }

        long time1 = System.currentTimeMillis();
        // 执行本身的代码
        Object result = invocation.proceed();
        long time2 = System.currentTimeMillis();
        System.out.println("拦截sql语句:" + removeBreakingWhitespace(boundSql.getSql()));
        System.out.println("执行完成耗时:" + (time2 - time1) + "ms");
        return result;
    }

    /**
     * 格式化sql语句
     * @param original
     * @return
     */
    protected String removeBreakingWhitespace(String original) {
        StringTokenizer whitespaceStripper = new StringTokenizer(original);
        StringBuilder builder = new StringBuilder();
        while (whitespaceStripper.hasMoreTokens()) {
            builder.append(whitespaceStripper.nextToken());
            builder.append(" ");
        }
        return builder.toString();
    }

    @Override
    public Object plugin(Object target) {
        /**
         * 一般使用mybatis自带生成动态代理方法wrap即可
         */
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

主要流程

1、使用@Intercepts和@Signature表明需要拦截的方法,这里拦截Executor对象的query方法,query方法有重载,有4个参数和6个参数的,这里都进行拦截

2、实现plugin方法,这里直接调用Plugin的wrap方法。wrap源码

public static Object wrap(Object target, Interceptor interceptor) {
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    Class<?> type = target.getClass();
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    if (interfaces.length > 0) {
      // 核心代码
      return Proxy.newProxyInstance(
          type.getClassLoader(),
          interfaces,
          new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }

核心代码处,使用了动态代理模式创建了一个代理对象,也就是我们传入的Executor对象被封装为了一个代理对象,当Executor的query方法被调用时会被代理转发到Plugin类的invoke方法,这就是jdk的动态代理模式

我们再看Plugin类的invoke方法

@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      if (methods != null && methods.contains(method)) {
      	// 核心代码
        return interceptor.intercept(new Invocation(target, method, args));
      }
      return method.invoke(target, args);
    } catch (Exception e) {
      throw ExceptionUtil.unwrapThrowable(e);
    }
  }

根据传入的插件类intercept,调用了它的intercept方法,进而回调回了我们LogInterceptor 实现的intercept方法,在intercept方法里面就可以实现我们自己的逻辑了

3、把我们自己的LogInterceptor 注册到Mybatis中

@Configuration
public class LogInterceptorConfig {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactoryList;

    @PostConstruct
    public void addPageInterceptor() {
        // 注册插件
        LogInterceptor interceptor = new LogInterceptor();
        Iterator var3 = this.sqlSessionFactoryList.iterator();
        while(var3.hasNext()) {
            SqlSessionFactory sqlSessionFactory = (SqlSessionFactory)var3.next();
            sqlSessionFactory.getConfiguration().addInterceptor(interceptor);
        }
    }

}

至此Mybatis的插件机制源码及简单案例都已经了解了,可以看到其中的核心逻辑就是提供了Interceptor接口供我们注册,Mybatis的插件机制使用的场景也非常多,比如比较常见的分页插件PageHelper就是基于插件实现的。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值