SqlSession
- SqlSession是一个会话,相当于jdbc的Connection对象,生命周期应该是请求数据库处理事务的过程中。它是非线程安全的,在每次创建SqlSession都必须及时关闭它,它长期存在就会使数据库连接池的活动资源减少。
SqlSession下的四大对象
- Mapper执行的过程是通过Executor、StatementHandler、ParameterHandler和ResultHandler来完成数据库操作和结果返回的
- Executor表示执行器,调度相关的handler来执行对应的sql(StatementHandler、ParameterHandler、ResultHandler)
- StatementHandler的作用是使用数据库的Statement(PreparedStatement)执行操作
- ParameterHandler用于SQL对参数的处理
- ResultHandler是进行最后数据集(ResultSet)的封装返回处理的
Executor
- Executor是一个真正执行java和数据库交互的东西
- SIMPLE
- REUSE
- BATCH
创建
在DefaultSqlSessionFactory中创建DefaultSqlSession之前创建Executor(通过Configuration创建),以下是Configuration中创建Executor的代码。根据配置类型去创建三种执行器中的一种,在创建之后将Executor放到interceptorChain之中 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); } if (cacheEnabled) { executor = new CachingExecutor(executor); } executor = (Executor) interceptorChain.pluginAll(executor); return executor; }
SimpleExecutor