当解析完配置文件后会返回一个configuration作为sqlSessionFactory:
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
这里面包含了所有的mapper以及各种配置,下面我们就来看一下他是如何打开一个会话的:
SqlSession session = sqlSessionFactory.openSession();
这是我们的入口代码:
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
从configuration里面获得一个默认的执行器,作为参数为我们打开一个会话:
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);
//返回一个包含执行器,是否开启了事务,以及配置信息的session
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();
}
}
这个方法主要就是为我们创建了一个事务,创建了一个执行器,最后将他们封装后构建了一个sqlSession返回
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);
}
//判断是否开启了二级缓存,如果开启了封装执行器变成CachingExecutor
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
下一篇文章我们就要看是如何执行一个数据库操作的。