mybatis session创建过程(2)
2018-07-05 本文已影响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组件类关系图