本文共 3048 字,大约阅读时间需要 10 分钟。
openSession()
openSessionFromDataSource()
tx
newExecutor()
Executor
在全局配置中的类型,创建出SimpleExecutor/ReuseExecutor/BatchExecutor
CachingExecutor(executor)
executor
并返回DefaultSqlSession
,包含Configuration
和Executor
DefaultSqlSession
openSession()
SqlSession openSession = sqlSessionFactory.openSession();
openSessionFromDataSource()
从configuration
中拿到默认的Executor
类型。Executor
类型的类型有三种:SIMPLE/REUSE/BATCH
。
@Override public SqlSession openSession() { return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false); }
tx
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(); } }
newExecutor()
传入的参数为事务管理器和Executor
的类型,根据传入的类型来创建Executor
,Executor
是一个接口,是用来增删改查的。
final Executor executor = configuration.newExecutor(tx, execType);
Executor
在全局配置中的类型,创建出SimpleExecutor/ReuseExecutor/BatchExecutor
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 = (Executor) interceptorChain.pluginAll(executor); return executor; }
CachingExecutor(executor)
对二级缓存的具体操作:
public CachingExecutor(Executor delegate) { this.delegate = delegate; delegate.setExecutorWrapper(this); }
executor
并返回pluginAll
具体实现:拿到所有的拦截器,调用每一个拦截器的plugin
方法。
public Object pluginAll(Object target) { for (Interceptor interceptor : interceptors) { target = interceptor.plugin(target); } return target; }
DefaultSqlSession
,包含Configuration
和Executor
DefaultSqlSession
总结:
DefaultSqlSession
是sqlSession
的实现类,里面包含了Executor
和Configuration
,Executor
在这一步会被创建。 转载地址:http://mpwc.baihongyu.com/