mybatis笔记-Executor

1.概念

MyBatis执行器,是MyBatis 调度的核心,负责SQL语句的生成和查询缓存的维护

2.类定义以及继承关系

2.1类定义

mybatis笔记-Executor_第1张图片

2.2继承关系

mybatis笔记-Executor_第2张图片
  1. SimpleExecutor -- SIMPLE 就是普通的执行器。
  2. ReuseExecutor -执行器会重用预处理语句(prepared statements)
  3. BatchExecutor --它是批量执行器

3.Executor的构建

3.1configuration的setting中配置defaultExecutorType

mybatis笔记-Executor_第3张图片

3.2在Configuration中根据defaultExecutorType来构建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;
  }

4.Executor示例

4.1ReuseExecutor

重用Statement,所以Statement使用完毕后并不会关闭,其以sql字符串作为key

  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    BoundSql boundSql = handler.getBoundSql();
    String sql = boundSql.getSql();
    if (hasStatementFor(sql)) {
      stmt = getStatement(sql);
      applyTransactionTimeout(stmt);
    } else {
      Connection connection = getConnection(statementLog);
      stmt = handler.prepare(connection, transaction.getTimeout());
      putStatement(sql, stmt);
    }
    handler.parameterize(stmt);
    return stmt;
  }

测试代码:
相同sql语句,传入不同参数时则会重用Statement

  @Test
  public void shouldSelectOneAuthor() throws Exception {
    SqlSession session = sqlMapper.openSession();
    try {

      for (int i=0;i<10;i++)
      {
        Author author = session.selectOne(
                "org.apache.ibatis.domain.blog.mappers.AuthorMapper.selectAuthor", new Author(101+i));
//        assertEquals(101, author.getId());
//        assertEquals(Section.NEWS, author.getFavouriteSection());
      }
    } finally {
      session.close();
    }
  }

4.2 BatchExecutor批处理

http://elim.iteye.com/blog/2353672

参考:
https://blog.csdn.net/ykzhen2015/article/details/50315027

你可能感兴趣的:(mybatis笔记-Executor)