美文网首页mybatis
mybatis session创建过程(2)

mybatis session创建过程(2)

作者: 晴天哥_王志 | 来源:发表于2018-07-05 19:03 被阅读32次

    session创建过程

     在mybatis的常规用法当中,通过sqlSessionFactory.openSession()来创建SqlSession对象,这里的sqlSessionFactory就是在解析配置后生成的SqlSession的工厂。

    public class MyBatisTest {
        public static void main(String[] args) throws Exception {
            String resource = "configuration.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(reader);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            User user = sqlSession.selectOne("userTest.selectUser", 1);
            System.out.println(user.getUsername());
            sqlSession.close();
        }
    }
    



    在openSession过程中我们按照下面顺序创建SqlSession对象

    • 生成mybatis的Environment对象
    • 生成TransactionFactory对象
    • 生成Transaction对象
    • 生成Executor对象
    • 生成DefaultSqlSession对象
      public SqlSession openSession() {
        return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
      }
    
    
      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);
          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 TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
        if (environment == null || environment.getTransactionFactory() == null) {
          return new ManagedTransactionFactory();
        }
        return environment.getTransactionFactory();
      }
    

    session组件依赖图

     通过下面这个图基本上把mybatis里面几个组件的创建顺序描述清楚了。


    mybatis组件关系图

    session组件类关系图

     通过下面这个图,基本上就把mybatis里面核心的几个类的继承包含关系描述清楚了。


    mybatis组件类关系图

    相关文章

      网友评论

        本文标题:mybatis session创建过程(2)

        本文链接:https://www.haomeiwen.com/subject/offpuftx.html