mybatis四大金刚之executor执行器

mybatis四大金刚之executor执行器

configuration.newExecutor()所有流程的开始

public class DefaultSqlSession {

  @Override
  public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
    try {
      MappedStatement ms = configuration.getMappedStatement(statement);
      return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error querying database.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }
}

Executor的主流程

mybatis执行器,通过拼接出sql,调用StatementHanlder执行database操作,以及缓存的子类可以重用预处理语句

(本节展示的源码代码,为了帮助同学们,减少干扰理解executor的执行流程省略了一些代码。)

public abstract class BaseExecutor implements Executor{

  @Override
  public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    // 省略部分代码
    List<E> list;
    //从db查询
    list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
    return list;
  }

  private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    List<E> list;
    // doQuery方法的具体实现在BaseExecutor的子类,这里使用了模板方法的设计模式: 
    list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
     return list;
  }

设计模式 - 模版方法

模板方法: 父类封装整个算法步骤,将某些步骤延迟到子类实现,使得不需要改变算法结构的情况下,重新定义算法中的某些步骤

默认的执行器SimpleExecutor

来看看怎么选的默认处理器

public enum ExecutorType {
  SIMPLE, REUSE, BATCH
}

public class Configuration{
    //默认值
    protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;

  //根据executorTypec返回Executor的子类
  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;
  }
}

简单的执行器,根据对应sql拼接完成后,直接交给StatementHanlder去执行

public class SimpleExecutor extends BaseExecutor{
  @Override
  public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Statement stmt = null;
    try {
      Configuration configuration = ms.getConfiguration();
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      stmt = prepareStatement(handler, ms.getStatementLog());
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    Connection connection = getConnection(statementLog);
    stmt = handler.prepare(connection, transaction.getTimeout());
    handler.parameterize(stmt);
    return stmt;
  }
}

执行器的类图

Executor BaseExecutor CachingExecutor SimpleExecutor ReuseExecutor BatchExecutor

可以看到BaseExecutor实现了Executor; SimpleExecutor,ReuseExecutor,BatchExecutor继承了BaseExecutor,
把具体的操作细节方法: doUpdate、doFlushStatements、doQuery、doQueryCursor通过模板方法交给不同的子类实现的。

SimpleExecutor : 简单的执行器
ReuseExecutor : 可重用执行器
BatchExecutor : 批处理执行器

那CachingExecutor这个类是做什么用的呢,我们在后面通过阅读源码同学们就知道具体是做什么的了,我们单单看累的名字记住它是一个缓存执行器。

ReuseExecutor可重用执行器

看名字,我们就知道这个处理器的作用是重复执行,如果已经在当前线程生命周期内查询过了,不需要在重新创建Statement了。我们直接看它的doquery方法,因为它的逻辑和simpleExecutor的区别就在doQuery这几个方法

  
public class ReuseExecutor extends BaseExecutor {

    //存储未预编译的sql于带 "?"
    private final Map<String, Statement> statementMap = new HashMap<String, Statement>();

  @Override
  public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    Configuration configuration = ms.getConfiguration();
    StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
    Statement stmt = prepareStatement(handler, ms.getStatementLog());
    return handler.<E>query(stmt, resultHandler);
  }

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    BoundSql boundSql = handler.getBoundSql();
    String sql = boundSql.getSql();
    if (hasStatementFor(sql)) {
    //如果当前线程存在sql,则获取到map存储的,不需要在创建了
      stmt = getStatement(sql);
      applyTransactionTimeout(stmt);
    } else {
    //没有则创建,并且缓存到map中
      Connection connection = getConnection(statementLog);
      stmt = handler.prepare(connection, transaction.getTimeout());
      putStatement(sql, stmt);
    }
    handler.parameterize(stmt);
    return stmt;
  }

  
  private Statement getStatement(String s) {
    return statementMap.get(s);
  }

  private void putStatement(String sql, Statement stmt) {
    statementMap.put(sql, stmt);
  }

}

注意这里的缓存仅在当前线程内有效。

如何开启的mybatis.xml配置方式是


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration 核心配置文件 -->
<configuration>

    <settings>
        <setting name="defaultExecutorType" value="REUSE"/>
    </settings>
</configuration>

BatchExecutor

批量执行,只对修改操作生效,对查询不生效,只对当前线程中的同修改sql,可以直接复用之前的statement,
使用这个处理器时要和doFlushStatements、commit方法一起使用,当执行commit数据写入数据库

public class BatchExecutor extends BaseExecutor {

 private final List<BatchResult> batchResultList = new ArrayList<BatchResult>();
 private String currentSql;
 private MappedStatement currentStatement;


  @Override
  public int doUpdate(MappedStatement ms, Object parameterObject) throws SQLException {
    final Configuration configuration = ms.getConfiguration();
    final StatementHandler handler = configuration.newStatementHandler(this, ms, parameterObject, RowBounds.DEFAULT, null, null);
    final BoundSql boundSql = handler.getBoundSql();
    final String sql = boundSql.getSql();
    final Statement stmt;
    // 如果sql存在使用之前的statement
    if (sql.equals(currentSql) && ms.equals(currentStatement)) {
      int last = statementList.size() - 1;
      stmt = statementList.get(last);
      applyTransactionTimeout(stmt);
      handler.parameterize(stmt);//fix Issues 322
      BatchResult batchResult = batchResultList.get(last);
      batchResult.addParameterObject(parameterObject);
    } else {
      Connection connection = getConnection(ms.getStatementLog());
      stmt = handler.prepare(connection, transaction.getTimeout());
      handler.parameterize(stmt);    //fix Issues 322
      currentSql = sql;
      currentStatement = ms;
      statementList.add(stmt);
      batchResultList.add(new BatchResult(ms, sql, parameterObject));
    }
  // handler.parameterize(stmt);
    handler.batch(stmt);
    return BATCH_UPDATE_RETURN_VALUE;
  }

}

BatchExecutor和ReuseExecutor很像区别就在于,ReuseExecutor复用了直接操作数据库,而batch则是最后一起提交写入数据库,可以节省网络通信时间。

如何开启的mybatis.xml配置方式是


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- configuration 核心配置文件 -->
<configuration>

    <settings>
        <setting name="defaultExecutorType" value="BATCH"/>
    </settings>
</configuration>

CachingExecutor

CachingExecutor表示启动二级缓存,默认开启。

public class Configuration{
  public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
      //根据配置或默认值创建SimpleExecutor、ReuseExecutor、BatchExecutor执行器
    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);
    }
    //缓存默认开启,创建CachingExecutor
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

}

public class CachingExecutor implements Executor {

  public CachingExecutor(Executor delegate) {
    this.delegate = delegate;
    delegate.setExecutorWrapper(this);
  }

 @Override
  public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
        //这里使用了装饰模式,引入了二级缓存功能
    Cache cache = ms.getCache();
    if (cache != null) {
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, parameterObject, boundSql);
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
            //调用被装饰者
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    //调用被装饰者
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }
}

回顾总结

1.BaseExecutor有三个子类SimpleExecutor、ReuseExecutor、BatchExecutor
2.BaseExecutor通过设计模式中的模板方法把doUpdate、doFlushStatements、doQuery、doQueryCursor的不同实现细节交给了子类
3.ReuseExecutor可重用执行器,避免同sql重复创建statement,注意这里的缓存仅在当前线程内有效
4.BatchExecutor比ReuseExecutor节省网络通信时间
5.mybatis通过CachingExecutor这个类实现了装饰者模式,不侵入SimpleExecutor、ReuseExecutor、BatchExecutor类增加了缓存功能

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值