前面已经介绍了初始化sqlsessionFactory对象时是如何加载mybatis配置文件的各个节点的。在初始化sqlsessionFactory对象后,我们可以通过该对象创建sqlSession对象,主要是两种创建方式:
1)sqlSessionFactory.openSession(boolean autoCommit)
2)sqlSessionFactory.openSession();
autoCommit的作用主要是mybatis执行sql操作完成后是否自动提交,如果autoCommit为true,则自动提交事务,否则需要手动提交事务。
下面来看下sqlSessionFactory对象是如何创建sqlSession对象的。
sqlSessionFactory.openSession(autoCommit)
//configuration.getDefaultExecutorType():如果未在mybatis配置文件settings节点中配置defaultExecutorType的值,则默认未simple
public SqlSession openSession(boolean autoCommit) {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, autoCommit);
}
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); //创建executor对象
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();
}
}
//mybatis中有两种事务管理器:
//1)如果是配置的为JDBC,则直接使用jdbc的事务
//2)如果是配置的MANAGED,则是让容器来管理事务,例如mybatis与spring整合,则让spring容器来管理事务。
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);

final Executor executor = configuration.newExecutor(tx, execType);
//在sqlSession对象中,执行都是通过executor对象来进行的
//来看下如何创建executor对象的
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
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); //因为我们这配置文件中未配置defaultExecutorType的值,默认未simple
}
if (cacheEnabled) { //如果在mybatis配置文件中settings节点中配置了开启缓存cacheEnabled,则executor的后续操作直接从缓存中读取
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor); //前面配置的plugins节点,后面可以在executor执行操作时进行拦截处理
return executor;
}
public Object pluginAll(Object target) {
for (Interceptor interceptor : interceptors) {
target = interceptor.plugin(target);
}
return target;
}
//创建defaultSqlSession对象
public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
this.configuration = configuration;
this.executor = executor;
this.dirty = false; //注意这个属性,在执行commit()与rollback()方法时,会用到这个属性
this.autoCommit = autoCommit;
}
浙公网安备 33010602011771号