2.8、mybatis源码分析之创建SqlSession流程

2018-09-19  本文已影响0人  小manong

一、mybatis接口层

1、SqlSession是mybatis的核心接口之一,是myabtis接口层的主要组成部分,对外提供了mybatis常用的api。myabtis提供了两个SqlSesion接口的实现,常用的实现类是DefaultSqlSession。
2、SqlSessionFactory负责创建SqlSession,其中包含多个openSession方法的重载,具体创建在DefaultSqlSessionFactory实现类中。

1、DefaultSqlSession

public class DefaultSqlSession implements SqlSession {
//configuration配置对象
  private final Configuration configuration;
//数据库操作相关的executor接口(策略模式)
  private final Executor executor;
//是否自动提交
  private final boolean autoCommit;
//当前缓存中是否有脏数据
  private boolean dirty;
//为防止用户忘记关闭打开的游标对象,会通过cursorList字段记录由该sqlsession对象生成的游标对象
  private List<Cursor<?>> cursorList;

2、DefaultSqlSessionFactory

 private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
    Transaction tx = null;
    try {
//获取配置的environment对象
      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();
    }
  }
private SqlSession openSessionFromConnection(ExecutorType execType, Connection connection) {
    try {
      boolean autoCommit;
      try {
        autoCommit = connection.getAutoCommit();
      } catch (SQLException e) {
        // Failover to true, as most poor drivers
        // or databases won't support transactions
        autoCommit = true;
      }      
      final Environment environment = configuration.getEnvironment();
      final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
      final Transaction tx = transactionFactory.newTransaction(connection);
      final Executor executor = configuration.newExecutor(tx, execType);
      return new DefaultSqlSession(configuration, executor, autoCommit);
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }

二、Executor接口

1、BaseExecutor

public abstract class BaseExecutor implements Executor {
  private static final Log log = LogFactory.getLog(BaseExecutor.class);
//实现事务的提交和回滚和关闭操作
  protected Transaction transaction;
//封装executor对象
  protected Executor wrapper;
//延迟队列
  protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
//一级缓存用于该Executor对象查询结果集映射得到的结果对象
  protected PerpetualCache localCache;
//一级缓存用于缓存输出类型的参数
  protected PerpetualCache localOutputParameterCache;
  protected Configuration configuration;
  protected int queryStack;
  private boolean closed;
其他方法

2、SimpleExecutor

  @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
      StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
      stmt = prepareStatement(handler, ms.getStatementLog());
//执行StatementHandler.query方法执行sql语句并通过ResultSetHandler完成结果集映射。
      return handler.<E>query(stmt, resultHandler);
    } finally {
      closeStatement(stmt);
    }
  }
  private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    Connection connection = getConnection(statementLog);
//创建Statement对象
    stmt = handler.prepare(connection, transaction.getTimeout());
//处理占位符号
    handler.parameterize(stmt);
    return stmt;
  }

2、ReuseExecutor

 private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
    Statement stmt;
    BoundSql boundSql = handler.getBoundSql();
//获取sql语句
    String sql = boundSql.getSql();
    if (hasStatementFor(sql)) {
      stmt = getStatement(sql);
//修改超时时间
      applyTransactionTimeout(stmt);
    } else {
//获取数据库连接并创建Statement并缓存发哦StatementMap中
      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 boolean hasStatementFor(String sql) {
    try {
      return statementMap.keySet().contains(sql) && !statementMap.get(sql).getConnection().isClosed();
    } catch (SQLException e) {
      return false;
    }
  }
  private void putStatement(String sql, Statement stmt) {
    statementMap.put(sql, stmt);
  }

4、BatchExecutor

public class BatchExecutor extends BaseExecutor {
    //缓存多个statement对象,其中每一个statement对象中都缓存可许多条sql语句
  private final List<Statement> statementList = new ArrayList<Statement>();
  //记录批处理的结果
  private final List<BatchResult> batchResultList = new ArrayList<BatchResult>();
  //当前的sql语句
  private String currentSql;
  //当前的MappedStatement对象
  private MappedStatement currentStatement;

  public BatchExecutor(Configuration configuration, Transaction transaction) {
    super(configuration, transaction);
  }

  @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模式与上次执行的sql模式相同且对应的MappedStatement对象相同
    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));
    }
  // 底层使用statement.addBatch方法添加sql语句
    handler.batch(stmt);
    return BATCH_UPDATE_RETURN_VALUE;
  }

5、CacheExecutor

三、创建SqlSession流程

1、DefaultSqlSessionFactory的openSession()方法

public SqlSession openSession() {
  /*
  configuration.getDefaultExecutorType()是获取ExecutorType类型,在Config配置文件中可以配置
   有三种形式SIMPLE(普通的执行器;), REUSE(执行器会重用预处理语句), BATCH(执行器将重用语句并执行批量更新),
默认的是SIMPLE
  */
    return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
  }

2、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);
    }
      //如果要求缓存,生成另一种CachingExecutor(默认就是有缓存),装饰者模式,所以默认都是返回CachingExecutor
    /**
      * 二级缓存开关配置示例
     * <settings>
     *   <setting name="cacheEnabled" value="true"/>
     * </settings>
     */
    if (cacheEnabled) {
      executor = new CachingExecutor(executor);
    }
    //此处调用插件,通过插件可以改变Executor行为
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
  }

3、new DefaultSqlSession创建SqlSession对象

  public DefaultSqlSession(Configuration configuration, Executor 
executor, boolean autoCommit) {
    this.configuration = configuration;
    this.executor = executor;
    this.dirty = false;
    this.autoCommit = autoCommit;
  }

四、创建SqlSession流程图

创建SqlSession流程图
上一篇 下一篇

猜你喜欢

热点阅读