
正文
MyBatis 3源码解析(二)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
二、获取SqlSession对象

1.首先调用DefaultSqlSessionFactory 的 openSession 方法,代码如下:
@Override public SqlSession openSession() { //configuration.getDefaultExecutorType 是调用configuration的Executor执行器的类型,默认simple return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
- 下面是openSessionFromDataSource方法:
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) { Transaction tx = null; try { //从configuration中获取环境配置信息 final Environment environment = configuration.getEnvironment(); final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment); //获取一些信息,创建了一个事物 tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit); //根据Executor在configuration中的配置,创建一个新的Executor 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(); } }
创建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); } //如果二级缓存配置开启了,创建CachingExecutor if (cacheEnabled) { executor = new CachingExecutor(executor); } executor = (Executor) interceptorChain.pluginAll(executor); return executor; }
最后返回了DefaultSqlSession,DefaultSqlSession中包含配置信息。







