在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()都是使用新的事务和执行类