天天看點

mybatis攔截器實作原理

原文https://blog.csdn.net/weixin_39494923/article/details/91534658

一.背景

在很多業務場景下我們需要去攔截sql,達到不入侵原有代碼業務處理一些東西,比如:分頁操作,資料權限過濾操作,SQL執行時間性能監控等等,這裡我們就可以用到Mybatis的攔截器Interceptor

二.Mybatis核心對象介紹

從MyBatis代碼實作的角度來看,MyBatis的主要的核心部件有以下幾個:

  • Configuration 初始化基礎配置,比如MyBatis的别名等,一些重要的類型對象,如,插件,映射器,ObjectFactory和typeHandler對象,MyBatis所有的配置資訊都維持在Configuration對象之中
  • SqlSessionFactory SqlSession工廠
  • SqlSession 作為MyBatis工作的主要頂層API,表示和資料庫互動的會話,完成必要資料庫增删改查功能
  • Executor MyBatis執行器,是MyBatis 排程的核心,負責SQL語句的生成和查詢緩存的維護
  • StatementHandler 封裝了JDBC Statement操作,負責對JDBC statement 的操作,如設定參數、将Statement結果集轉換成List集合。
  • ParameterHandler 負責對使用者傳遞的參數轉換成JDBC Statement 所需要的參數,
  • ResultSetHandler 負責将JDBC傳回的ResultSet結果集對象轉換成List類型的集合;
  • TypeHandler 負責java資料類型和jdbc資料類型之間的映射和轉換
  • MappedStatement MappedStatement維護了一條<select|update|delete|insert>節點的封裝,
  • SqlSource 負責根據使用者傳遞的parameterObject,動态地生成SQL語句,将資訊封裝到BoundSql對象中,并傳回
  • BoundSql 表示動态生成的SQL語句以及相應的參數資訊

三. Mybatis執行概要圖

mybatis攔截器實作原理

四.MyBatis 攔截器原理實作

  1. Mybatis支援對Executor、StatementHandler、PameterHandler和ResultSetHandler 接口進行攔截,也就是說會對這4種對象進行代理
  2. 首先從配置檔案解析開始
  • 通過SqlSessionFactoryBean去建構Configuration添加攔截器并建構擷取SqlSessionFactory
/**
 * {@code FactoryBean} that creates an MyBatis {@code SqlSessionFactory}.
 * This is the usual way to set up a shared MyBatis {@code SqlSessionFactory} in a Spring application context;
 * the SqlSessionFactory can then be passed to MyBatis-based DAOs via dependency injection.
 *
 * Either {@code DataSourceTransactionManager} or {@code JtaTransactionManager} can be used for transaction
 * demarcation in combination with a {@code SqlSessionFactory}. JTA should be used for transactions
 * which span multiple databases or when container managed transactions (CMT) are being used.
 *
 * @author Putthibong Boonbong
 * @author Hunter Presnall
 * @author Eduardo Macarron
 * @author Eddú Meléndez
 * @author Kazuki Shimizu
 *
 * @see #setConfigLocation
 * @see #setDataSource
 */
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
 
    private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class);
 
    private Resource configLocation;
 
    private Configuration configuration;
 
    private Resource[] mapperLocations;
 
    private DataSource dataSource;
 
    private TransactionFactory transactionFactory;
 
    private Properties configurationProperties;
 
    private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
 
    // ... 此處省略部分源碼
 
    /**
     * Build a {@code SqlSessionFactory} instance.
     *
     * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a
     * {@code SqlSessionFactory} instance based on an Reader.
     * Since 1.3.0, it can be specified a {@link Configuration} instance directly(without config file).
     *
     * @return SqlSessionFactory
     * @throws IOException if loading the config file failed
     */
    protected SqlSessionFactory buildSqlSessionFactory() throws IOException {
 
 
        Configuration configuration;
        // 根據配置資訊建構Configuration實體類
        XMLConfigBuilder xmlConfigBuilder = null;
        if (this.configuration != null) {
            configuration = this.configuration;
            if (configuration.getVariables() == null) {
                configuration.setVariables(this.configurationProperties);
            } else if (this.configurationProperties != null) {
                configuration.getVariables().putAll(this.configurationProperties);
            }
        } else if (this.configLocation != null) {
            xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties);
            configuration = xmlConfigBuilder.getConfiguration();
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration");
            }
            configuration = new Configuration();
            if (this.configurationProperties != null) {
                configuration.setVariables(this.configurationProperties);
            }
        }
 
        // ... 此處省略部分源碼
 
        if (hasLength(this.typeAliasesPackage)) {
            String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage,
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
            for (String packageToScan : typeAliasPackageArray) {
                configuration.getTypeAliasRegistry().registerAliases(packageToScan,
                        typeAliasesSuperType == null ? Object.class : typeAliasesSuperType);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases");
                }
            }
        }
 
        if (!isEmpty(this.typeAliases)) {
            for (Class<?> typeAlias : this.typeAliases) {
                configuration.getTypeAliasRegistry().registerAlias(typeAlias);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Registered type alias: '" + typeAlias + "'");
                }
            }
        }
        // 檢視是否注入攔截器,有的話添加到Interceptor集合裡面
        if (!isEmpty(this.plugins)) {
            for (Interceptor plugin : this.plugins) {
                configuration.addInterceptor(plugin);
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Registered plugin: '" + plugin + "'");
                }
            }
        }
 
        // ... 此處省略部分源碼
 
        return this.sqlSessionFactoryBuilder.build(configuration);
    }
 
    // ... 此處省略部分源碼
}

           
  • 通過原始的XMLConfigBuilder 建構configuration添加攔截器
public class XMLConfigBuilder extends BaseBuilder {
    //解析配置
    private void parseConfiguration(XNode root) {
        try {
            //省略部分代碼
            pluginElement(root.evalNode("plugins"));
 
        } catch (Exception e) {
            throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        }
    }
 
    private void pluginElement(XNode parent) throws Exception {
        if (parent != null) {
            for (XNode child : parent.getChildren()) {
                String interceptor = child.getStringAttribute("interceptor");
                Properties properties = child.getChildrenAsProperties();
                Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).newInstance();
                interceptorInstance.setProperties(properties);
                //調用InterceptorChain.addInterceptor
                configuration.addInterceptor(interceptorInstance);
            }
        }
    }
}
           

上面是兩種不同的形式建構configuration并添加攔截器interceptor,上面第二種一般是以前XML配置的情況,這裡主要是解析配置檔案的plugin節點,根據配置的interceptor 屬性執行個體化Interceptor 對象,然後添加到Configuration 對象中的InterceptorChain 屬性中

3.定義了攔截器鍊,初始化配置檔案的時候就把所有的攔截器添加到攔截器鍊中

org.apache.ibatis.plugin.InterceptorChain 源代碼如下:

public class InterceptorChain {
 
 
  private final List<Interceptor> interceptors = new ArrayList<Interceptor>();
 
  public Object pluginAll(Object target) {
    //循環調用每個Interceptor.plugin方法
    for (Interceptor interceptor : interceptors) {
      target = interceptor.plugin(target);
    }
    return target;
  }
   // 添加攔截器
  public void addInterceptor(Interceptor interceptor) {
    interceptors.add(interceptor);
  }
  
  public List<Interceptor> getInterceptors() {
    return Collections.unmodifiableList(interceptors);
  }
 
}

           

4.從以下代碼可以看出mybatis 在執行個體化Executor、ParameterHandler、ResultSetHandler、StatementHandler四大接口對象的時候調用interceptorChain.pluginAll() 方法插入進去的。其實就是循環執行攔截器鍊所有的攔截器的plugin() 方法,

mybatis官方推薦的plugin方法是Plugin.wrap() 方法,這個類就是我們上面的TargetProxy類

org.apache.ibatis.session.Configuration 類,其代碼如下:

public class Configuration {
 
    protected final InterceptorChain interceptorChain = new InterceptorChain();
    //建立參數處理器
    public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
        //建立ParameterHandler
        ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
        //插件在這裡插入
        parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
        return parameterHandler;
    }
 
    //建立結果集處理器
    public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
                                                ResultHandler resultHandler, BoundSql boundSql) {
        //建立DefaultResultSetHandler
        ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
        //插件在這裡插入
        resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
        return resultSetHandler;
    }
 
    //建立語句處理器
    public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        //建立路由選擇語句處理器
        StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
        //插件在這裡插入
        statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
        return statementHandler;
    }
 
    public Executor newExecutor(Transaction transaction) {
        return newExecutor(transaction, defaultExecutorType);
    }
 
    //産生執行器
    public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
        executorType = executorType == null ? defaultExecutorType : executorType;
        //這句再做一下保護,囧,防止粗心大意的人将defaultExecutorType設成null?
        executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
        Executor executor;
        //然後就是簡單的3個分支,産生3種執行器BatchExecutor/ReuseExecutor/SimpleExecutor
        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);
        }
        //如果要求緩存,生成另一種CachingExecutor(預設就是有緩存),裝飾者模式,是以預設都是傳回CachingExecutor
        if (cacheEnabled) {
            executor = new CachingExecutor(executor);
        }
        //此處調用插件,通過插件可以改變Executor行為
        executor = (Executor) interceptorChain.pluginAll(executor);
        return executor;
    }
}
           

5.Mybatis的Plugin動态代理

org.apache.ibatis.plugin.Plugin 源代碼如下

public class Plugin implements InvocationHandler {
 
    public static Object wrap(Object target, Interceptor interceptor) {
    //從攔截器的注解中擷取攔截的類名和方法資訊
    Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
    //取得要改變行為的類(ParameterHandler|ResultSetHandler|StatementHandler|Executor)
    Class<?> type = target.getClass();
    //取得接口
    Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
    //産生代理,是Interceptor注解的接口的實作類才會産生代理
    if (interfaces.length > 0) {
      return Proxy.newProxyInstance(type.getClassLoader(),interfaces,new Plugin(target, interceptor, signatureMap));
    }
    return target;
  }
    
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
      //擷取需要攔截的方法
      Set<Method> methods = signatureMap.get(method.getDeclaringClass());
      //是Interceptor實作類注解的方法才會攔截處理
      if (methods != null && methods.contains(method)) {
        //******調用Interceptor.intercept,也即插入了我們自己的邏輯********
        return interceptor.intercept(new Invocation(target, method, args));
      }
      //最後還是執行原來邏輯
        return method.invoke(target, args);
    } catch (Exception e) {
        throw ExceptionUtil.unwrapThrowable(e);
    }
  }
    
  //取得簽名Map,就是擷取Interceptor實作類上面的注解,要攔截的是那個類(Executor 
  //,ParameterHandler, ResultSetHandler,StatementHandler)的那個方法 
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
    //取Intercepts注解,例子可參見ExamplePlugin.java
    Intercepts interceptsAnnotation =interceptor.getClass().getAnnotation(Intercepts.class);
    // issue #251
    //必須得有Intercepts注解,沒有報錯
    if (interceptsAnnotation == null) {
      throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());      
    }
    //value是數組型,Signature的數組
      Signature[] sigs = interceptsAnnotation.value();
    //每個class裡有多個Method需要被攔截,是以這麼定義
      Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
     for (Signature sig : sigs) {
      Set<Method> methods = signatureMap.get(sig.type());
        if (methods == null) {
          methods = new HashSet<Method>();
          signatureMap.put(sig.type(), methods);
      }
      try {
         Method method = sig.type().getMethod(sig.method(), sig.args());
         methods.add(method);
      } catch (NoSuchMethodException e) {
         throw new PluginException("Could not find method on " + sig.type() + " named " + sig.method() + ". Cause: " + e, e);
      }
    }
    return signatureMap;
  }
    
 //取得接口
 private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) {
    Set<Class<?>> interfaces = new HashSet<Class<?>>();
      while (type != null) {
        for (Class<?> c : type.getInterfaces()) {
        //攔截其他的無效
        if (signatureMap.containsKey(c)) {
          interfaces.add(c);
        }
      }
      type = type.getSuperclass();
    }
    return interfaces.toArray(new Class<?>[interfaces.size()]);
  }
}
           

6.我們自己實作的攔截器

@Slf4j
@Component
@Intercepts({@Signature(method = "prepare", type = StatementHandler.class, args = {Connection.class, Integer.class}),
            @Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})})
@SuppressWarnings("unchecked")
public class SqliteDataSourceInterceptor implements Interceptor {
 
    @Override
    public Object plugin(Object target) {
        // 調用插件
        return Plugin.wrap(target, this);
    }
 
    @Override
    public void setProperties(Properties properties) {
    }
 
    @Override
    public Object intercept(Invocation invocation) throws Exception {
        // 該方法寫入自己的邏輯
        if (invocation.getTarget() instanceof StatementHandler) {
            String dataSoureType = DynamicDataSourceContextHolder.getDateSoureType();
            // judge dataSource type ,because sqlite can't use internal.core_project this express
            // so we need to add "" for it or delete this 'internal.'
            if (DataSourceType.SQLITE.name().equals(dataSoureType)) {
                RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();
                StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");
                BoundSql boundSql = delegate.getBoundSql();
                String sql = boundSql.getSql();
                sql = sql.replace("internal.", " ");
                ReflectUtil.setFieldValue(boundSql, "sql", sql);
            }
        }
        // SQL execute start time
        long startTimeMillis = System.currentTimeMillis();
        // get execute result
        Object proceedReslut = invocation.proceed();
        // SQL execute end time
        long endTimeMillis = System.currentTimeMillis();
        log.debug("<< ==== sql execute runnung time:{} millisecond ==== >>", (endTimeMillis - startTimeMillis));
        return proceedReslut;
    }
}
           

Mybatis攔截器用到責任鍊模式+動态代理+反射機制;

通過上面的分析可以知道,所有可能被攔截的處理類都會生成一個代理類,如果有N個攔截器,就會有N個代理,層層生成動态代理是比較耗性能的。而且雖然能指定插件攔截的位置,但這個是在執行方法時利用反射動态判斷的,初始化的時候就是簡單的把攔截器插入到了所有可以攔截的地方。是以盡量不要編寫不必要的攔截器;

附:如果采用SqlSessionFactoryBean的形式配置攔截器不起作用,需要在SqlSessionFactoryBean設定添加即可,如下紅框框

mybatis攔截器實作原理

個人部落格:https://www.xiaoxuya.top/