讀mybatis源碼之二:構建SqlSession邏輯

       在mybatis調用的時候,普通調用方式:

       

SqlSession session = sqlSessionFactory.openSession();
try {
  Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
  session.close();
}

      一、sqlSessionFactory:

      何處構建的呢? 是SqlSessionFactoryBuilder根據XML映射文件創建SqlSessionFactory。可以看見默認返回DefaultSqlSessionFactory
public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }

      二、sqlSessionFactory.openSession()

        DefaultSqlSessionFactory裏面openSession()來獲取SqlSession,主要看下面方法:
 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);
      final Executor executor = configuration.newExecutor(tx, execType, autoCommit);
      return new DefaultSqlSession(configuration, executor);
    } 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();
    }
  }

        通過配置類獲取環境對象,根據環境對象得到事務工廠,通過事務工廠得到一個新的事務。
        通過配置獲取一個新的執行類,最後返回DefaultSqlSession。
        可以看出,每次openSession()都是使用新的事務和執行類

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章