讲完了Configuration,我们继续回到我们的最初的SqlSession.
我们最初的切入点是SqlSessionFactory,而SqlSessionFactory的作用就是为了open一个SqlSession,我们来回顾一下所有openSession方法最终会调用的两个方法:
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 SqlSession openSessionFromConnection(ExecutorType execType, Connection connection) {
try {
boolean autoCommit;
try {
autoCommit = connection.getAutoCommit();
} catch (SQLException e) {
autoCommit = true;
}
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
final Transaction tx = transactionFactory.newTransaction(connection);
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
这两个方法之前也分析过,他们最终会返回一个SqlSession,由上述代码可以看到,最终返回的SqlSession的实现类DefaultSqlSession,并且其中传入了Configuration,Executor.
而Executor中需要传入Transaction.
Transaction在我们分析Configuration时也分析过,是一个事务,内部包含着一个数据库连接.所以之前我们也说过,最终的sql是由Executor去执行的.
我们先来看configuration.newExecutor方法:
// ExecutorType有三种类型,如下所示,默认情况下是SIMPLE,这里我们先理解为不同的类型会返回不同的实现类,具体三种的区别以后会分析
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
// 根据ExecutorType生成不同的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);
}
// 如果支持缓存,则使用CachingExecutor封装一层(cacheEnabled值默认为true,可在settings标签中配置)
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
// 一些plugins配置设置
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
public enum ExecutorType {
SIMPLE, REUSE, BATCH
}
SqlSession的创建我们就分析完了,之后,我们将分析SqlSession是怎样去执行各种sql语句的.