上一篇文章分析了 MyBatis 解析配置文件初始化的流程,本篇主要分析一下SqlSession 具体的执行流程。
MyBatis 在解析完配置文件后生成了一个 DefaultSqlSessionFactory
对象,后续执行 SQL 请求的时候都是调用其 openSession
方法获得 SqlSessison
,相当于一个 SQL 会话。 SqlSession
提供了操作数据库的一些方法,如 select
、update
等。
openSession
先看一下 DefaultSqlSessionFactory
的 openSession
的代码:
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
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);
// 每个 SqlSession 都有一个单独的 Executor 对象
final Executor executor = configuration.newExecutor(tx, execType, autoCommit);
// 返回 DefaultSqlSession 对象
return new DefaultSqlSession(configuration, executor);
} 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();
}
}
主要代码在 openSessionFromDataSource
,首先是从 Configuration
中取出相关的配置,生成 Transaction
,接着又创建了一个 Executor
,最后返回了 DefaultSqlSession
对象。
这里的 Executor
是什么呢?它其实是一个执行器,SqlSession
的操作会交给 Executor
去执行。MyBatis 的 Executor
常用的有以下几种:
- SimpleExecutor: 默认的 Executor,每个 SQL 执行时都会创建新的 Statement
- ResuseExecutor: 相同的 SQL 会复用 Statement
- BatchExecutor: 用于批处理的 Executor
- CachingExecutor: 可缓存数据的 Executor,用代理模式包装了其它类型的 Executor
了解了 Executor
的类型后,看一下 configuration.newExecutor(tx, execType, autoCommit)
的代码:
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
// 默认是 SimpleExecutor
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;
}
MyBatis 默认启用一级缓存,即同一个 SqlSession
会共用同一个缓存,上面代码最终返回的是 CachingExecutor
。
getMapper
我们看一下SqlSession的getMapper方法实现,一路点过去,可以看到SqlSession -> DefaultSqlSession->Configuration->MapperRegistry->MapperProxyFactory->MapperProxy
public class Configuration {
...
public <T> void addMapper(Class<T> type) {
this.mapperRegistry.addMapper(type);
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return this.mapperRegistry.getMapper(type, sqlSession);
}
}
public class MapperRegistry {
private final Configuration config;
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap();
public MapperRegistry(Configuration config) {
this.config = config;
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
} else {
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception var5) {
throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
}
}
}
public <T> boolean hasMapper(Class<T> type) {
return this.knownMappers.containsKey(type);
}
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (this.hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
this.knownMappers.put(type, new MapperProxyFactory(type));
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(this.config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
this.knownMappers.remove(type);
}
}
}
}
在创建了 SqlSession
之后,下一步是生成 Mapper 接口的代理类,代码如下:
public <T> T getMapper(Class<T> type) {
return configuration.<T>getMapper(type, this);
}
可以看出是从 configuration
中取得 Mapper
,最终调用了 MapperProxyFactory
的 newInstance
。MapperProxyFactory
在上一篇文章已经分析过,它是为了给 Mapper
接口生成代理类,其中关键的拦截逻辑在 MapperProxy
中,下面是其 invoke
方法:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
// 过滤一些不需要被代理的方法
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
// 从缓存中获取 MapperMethod 然后调用
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
MapperProxy
中调用了 MapperMethod
的 execute
,下面是部分代码:
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
...
}
可以看出,最终调用了 SqlSession
的对应方法,也就是 DefaultSqlSession
中的方法。
select
先看一下 DefaultSqlSession
中 select
的代码:
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
select
中调用了 executor
的 query
,上面提到,默认的 Executor
是 CachingExecutor
,看其中的代码:
@Override
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameterObject);
// 获取缓存的key
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
// 获取缓存
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {
list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
// 调用代理对象的缓存
return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
首先检查缓存中是否有数据,如果没有再调用代理对象的 query
,默认是 SimpleExecutor
。Executor
是一个接口,下面有个实现类是 BaseExecutor
,其中实现了其它 Executor
通用的一些逻辑,包括 doQuery
以及 doUpdate
等,其中封装了 JDBC 的相关操作。
update
update
的执行与 select
类似, 都是从 CachingExecutor
开始,看代码:
@Override
public int update(MappedStatement ms, Object parameterObject) throws SQLException {
// 检查是否需要刷新缓存
flushCacheIfRequired(ms);
// 调用代理类的 update
return delegate.update(ms, parameterObject);
}
update
会使得缓存的失效,所以第一步是检查是否需要刷新缓存,接下来再交给代理类去执行真正的数据库更新操作。
SqlSession下的四大对象
通过上面的分析,映射器就是一个动态代理对象,进入到了MapperMethod的execute方法,它经过简单的判断就进入了SqlSession的删除、更新、插入、选择等方法,这些方法如何执行是下面要介绍的内容。
Mapper执行的过程是通过Executor、StatementHandler、ParameterHandler和ResultHandler来完成数据库操作和结果返回的,理解他们是编写插件的关键:
- Executor:执行器,由它统一调度其他三个对象来执行对应的SQL;
- StatementHandler:使用数据库的Statement执行操作;
- ParameterHandler:用于SQL对参数的处理;
- ResultHandler:进行最后数据集的封装返回处理;
在MyBatis中存在三种执行器:
- SIMPLE:简易执行器,默认的执行器;
- REUSE:执行重用预处理语句;
- BATCH:执行重用语句和批量更新,针对批量专用的执行器;
以SimpleExecutor为例,说明执行过程
public class SimpleExecutor extends BaseExecutor {
/**
* 执行查询操作
*/
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.<E>query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
/**
* 初始化StatementHandler
*/
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection);
handler.parameterize(stmt);
return stmt;
}
/**
* 执行查询
*/
@Override
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
String sql = boundSql.getSql();
statement.execute(sql);
return resultSetHandler.<E>handleResultSets(statement);
}
}
可以看到最后会委托给StatementHandler会话器进行处理,它是一个接口,实际创建的是RoutingStatementHandler对象,但它不是真实的服务对象,它是通过适配器模式找到对应的StatementHandler执行的。在MyBatis中,StatementHandler和Executor一样分为三种:SimpleStatementHandler、PreparedStatementHandler、CallableStatementHandler。
Executor会先调用StatementHandler的prepare方法预编译SQL语句,同时设置一些基本运行的参数。然后调用parameterize()方法启用ParameterHandler设置参数,完成预编译,跟着执行查询,用ResultHandler封装结果返回给调用者。
总结
本文主要分析了 SqlSession
的执行流程,结合上一篇文章基本了解了 MyBatis 的运行原理。