Mybatis-Executor解析(二)

Executor的继承结构 

首先,最底层的接口是Executor,有两个实现类:BaseExecutor和CachingExecutor,CachingExecutor用于二级缓存,而BaseExecutor则用于一级缓存及基础的操作。并且由于BaseExecutor是一个抽象类,提供了三个实现:SimpleExecutor,BatchExecutor,ReuseExecutor,而具体使用哪一个Executor则是可以在mybatis-config.xml中进行配置的。配置如下:

<settings>
    <!--SIMPLE、REUSE、BATCH-->
    <setting name="defaultExecutorType" value="REUSE"/>
</settings>

如果没有配置Executor,默认情况下是SimpleExecutor。

各个Executor简单分析

对CachingExecutor我们暂时不分析,等在学习Mybatis缓存的时候再一并分析。

  1. SimpleExecutor是最简单的执行器,根据对应的sql直接执行即可,不会做一些额外的操作;
  2. BatchExecutor执行器,顾名思义,通过批量操作来优化性能。通常需要注意的是批量更新操作,由于内部有缓存的实现,使用完成后记得调用flushStatements来清除缓存。
  3. ReuseExecutor 可重用的执行器,重用的对象是Statement,也就是说该执行器会缓存同一个sql的Statement,省去Statement的重新创建,优化性能。内部的实现是通过一个HashMap来维护Statement对象的。由于当前Map只在该session中有效,所以使用完成后记得调用flushStatements来清除Map。
private final Map<String, Statement> statementMap = new HashMap<String, Statement>();
  1. 这几个Executor的生命周期都是局限于SqlSession范围内。

Executor初始化

大概了解了各个Executor的具体含义之后,我们来看一下Executor是如何初始化的。
我们以默认不配置 defaultExecutorType 情况下为例,并且不开启二级缓存。

<settings>
        <setting name="cacheEnabled" value="false"/>
    </settings>

我们还是以上文的例子来说:

InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionManager sessionManager = SqlSessionManager.newInstance(inputStream);
sessionManager.startManagedSession();
// 执行
String statement = "com.mapper.IStudentMapper.getAll";
List<Student> student = sessionManager.selectList(statement);
System.out.println(student);
  1. 第一步,首先我们获取SqlSessionManager,这里就不多说了,上文已经详细说过了;
  2. 第二步,我们调用startManagedSession方法来使SqlSessionManager内部维护的localSqlSession变量生效,这一步操作中会涉及到对Executor的获取,我们来看一下代码实现:

首先,我们调用startManagedSession:

public void startManagedSession() {
    this.localSqlSession.set(openSession());
}

在调用startManagedSession的过程中,会调用openSession来创建获取SqlSession:

public SqlSession openSession() {
    return sqlSessionFactory.openSession();
}

public SqlSession openSession() {
    // 这里会获取配置文件的defaultExecutorType属性
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}

在获取SqlSession的过程中会调用 openSessionFromDataSource来获取:

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);
      // 这里会获取Executor
      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();
    }
}

接着,这里会通过configuration.newExecutor来获取Executor:

public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
    // 根据不同的executorType来创建
    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);
    }
    // cacheEnabled 也就是我们配置的二级缓存,如果该值配置为true,则获取的是CachingExecutor
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    // 这里是通过责任链模式来生成代理对象
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}

而在newExecutor方法中,我们完成了对Executor的获取。

而在Executor执行对应的方法的时候,我们还有一点可以注意下,就是SqlSessionManager中代理对象的处理。代理对象会通过调用SqlSessionInterceptor的invoke方法来调用实际的方法。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      // 先从localSqlSession中获取SqlSession
      final SqlSession sqlSession = SqlSessionManager.this.localSqlSession.get();
      // 获取到,直接调用实际方法
      if (sqlSession != null) {
        try {
          return method.invoke(sqlSession, args);
        } catch (Throwable t) {
          throw ExceptionUtil.unwrapThrowable(t);
        }
      } else {
        // 获取不到,调用openSession获取
        final SqlSession autoSqlSession = openSession();
        try {
          final Object result = method.invoke(autoSqlSession, args);
          autoSqlSession.commit();
          return result;
        } catch (Throwable t) {
          autoSqlSession.rollback();
          throw ExceptionUtil.unwrapThrowable(t);
        } finally {
          autoSqlSession.close();
        }
      }
}

总结

  1. Mybatis一次会话中对数据库的增删改查是通过Executor来实现的;
  2. Executor的结构比较简单,其中我们只需注意下它的体系结构及初始化方式;
  3. BaseExecutor这里采用了模板方法模式,值得我们学习下;

猜你喜欢

转载自blog.csdn.net/pyd950812/article/details/90081930
今日推荐