前面我们介绍了mapper接口是如何获取的,那么接下来就是具体的调用Mapper方法执行SQL:
User user = userMapper.getById(1L);
话不多说,直接来看下具体的执行流程。
熟悉JDK动态代理的小伙伴应该都知道,代理类需要实现InvocationHandler接口,并重写里面的invoke方法。
public class MapperProxy<T> implements InvocationHandler, Serializable {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//........
}
}
也就是说获取mapper对象时,会获取到一个MapperProxyFactory工厂类,并创建一个MapperProxy代理类,在执行Mapper接口的方法时,会调用MapperProxy的invoke方法。
//org.apache.ibatis.binding.MapperProxy#invoke
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//判断是否需要去执行SQL还是直接执行方法
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);
}
//debug时method的值: public abstract com.wsh.mybatis.mybatisdemo.entity.User com.wsh.mybatis.mybatisdemo.mapper.UserMapper.getById(java.lang.Long)
//debug时args的值是一个数组: [1]
//获取缓存,保存了方法签名和接口方法的关系
final MapperMethod mapperMethod = cachedMapperMethod(method);
//真正执行方法是MapperMethod类的execute方法
return mapperMethod.execute(sqlSession, args);
}
我们在invoke方法里面打一个断点,观察一下具体的执行过程:
我们看到,invoke方法里面又是调用的MapperMethod的execute方法执行查询操作,继续跟踪源码:
//org.apache.ibatis.binding.MapperMethod#execute
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
//判断当前SQL的类型,是插入还是删除、还是更新、查询等
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;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
//将参数转换为SQL语句中参数,下面会详细介绍
Object param = method.convertArgsToSqlCommandParam(args);
//通过sqlSession执行查询
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional() &&
(result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
可以看到,execute方法里面主要做了两件事情:
下面分别进行介绍:
//org.apache.ibatis.binding.MapperMethod.MethodSignature#convertArgsToSqlCommandParam
public Object convertArgsToSqlCommandParam(Object[] args) {
//args: [1]
return paramNameResolver.getNamedParams(args);
}
继续追踪,查看getNamedParams()方法源码:
//org.apache.ibatis.reflection.ParamNameResolver#getNamedParams
public Object getNamedParams(Object[] args) {
//names: 0(key) -> id(value)
// args: [1]
//参数个数
final int paramCount = names.size();
//参数值为空或者参数个数为0的时候
if (args == null || paramCount == 0) {
return null;
} else if (!hasParamAnnotation && paramCount == 1) {
//只有一个参数并且没有写@Param注解的时候,直接返回第一个参数 args[0] = 1,即直接返回1
return args[names.firstKey()];
} else {
//参数不为空时,封装成map
final Map<String, Object> param = new ParamMap<>();
int i = 0;
//遍历names: {0 = id}
for (Map.Entry<Integer, String> entry : names.entrySet()) {
//args: [1]
//将names的value, 即id作为key
//将names的key,即0,作为从args数组的下标去获取参数值, 也就是args[0]=1
//param: id -> 1, 也就是id的值就对应上1这个值了.
param.put(entry.getValue(), args[entry.getKey()]);
// add generic param names (param1, param2, ...)
//同时,除了前面的#{id}=1,Mybatis还是自动生成param1、param2等参数
//对应到Mapper接口的第一个、第二个参数.
//注意从1开始, param1...paramN
final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
// ensure not to overwrite parameter named with @Param
if (!names.containsValue(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
如上我们知道了getNamedParams()方法主要完成了对mapper接口参数名称的生成,使用map进行包装,即@Param("xxx")、param1等,以至于我们在XML中可以使用到这些注解。
如下图,经过getNamedParams方法后,Mybatis帮我们组装好了参数名称以及参数值得对应关系。
SQL参数获取成功后, 接下来就是执行sql语句,及返回结果:
//org.apache.ibatis.session.SqlSession#selectOne(java.lang.String, java.lang.Object)
//其实是调用selectList()方法获取第一条数据的
//其中参数statement就是statement的id,parameter就是参数
<T> T selectOne(String statement, Object parameter);
//org.apache.ibatis.session.defaults.DefaultSqlSession#selectOne(java.lang.String, java.lang.Object)
public <T> T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
//parameter: id -> 1、param1 -> 1
List<T> list = this.selectList(statement, parameter);
if (list.size() == 1) {
//结果集长度等于一,直接返回第一个结果
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
继续跟踪,来到DefaultSqlSession的selectList方法:
//org.apache.ibatis.session.defaults.DefaultSqlSession#selectList(java.lang.String, java.lang.Object, org.apache.ibatis.session.RowBounds)
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
//第一步:获取到MappedStatement对象
//根据statement作为map的key,从之前解析之后保存在configuration中的[Map<String, MappedStatement> mappedStatements]中找到MappedStatement
MappedStatement ms = configuration.getMappedStatement(statement);
//第二步:通过executor执行器执行对应的SQL,将参数传递进去
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
可以看到,selectList方法主要做了两件事情:
继续看query方法的源码:
//org.apache.ibatis.executor.CachingExecutor#query(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler)
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
//获取到具体的SQL语句
BoundSql boundSql = ms.getBoundSql(parameterObject);
//执行查找,并开启加入缓存,mybatis缓存是默认开启的
//key = 1067688838:2080526037:com.wsh.mybatis.mybatisdemo.mapper.UserMapper.getById:0:2147483647:select * from user where id = ?:1:development
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
首先获取到执行查询的SQL语句,然后创建缓存key值,最后调用重载的query方法执行查询:
//org.apache.ibatis.executor.CachingExecutor#query(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler, org.apache.ibatis.cache.CacheKey, org.apache.ibatis.mapping.BoundSql)
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
//第一步:通过MappedStatement获取到二级缓存
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.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
//如果二级缓存为空,直接普通查询
return delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
delegate.query()方法源码:
//org.apache.ibatis.executor.BaseExecutor#query(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler, org.apache.ibatis.cache.CacheKey, org.apache.ibatis.mapping.BoundSql)
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
//flushCache=true 的时候,会先清理本地缓存(一级缓存)
if (queryStack == 0 && ms.isFlushCacheRequired()) {
//清空本地缓存
clearLocalCache();
}
List<E> list;
try {
queryStack++;
//第一步:判断一级缓存中是否存在数据,有的话直接从一级缓存中取
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
//第二步:没有缓存则直接从数据库中查询 queryFromDatabase
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
由于是第一次查询,一级、二级缓存中肯定都没有对应的数据,所以执行的是从数据库中查询:
//org.apache.ibatis.executor.BaseExecutor#queryFromDatabase
//从数据库中查询数据
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
//存入缓存
//localCache里面有一个Map用来缓存:private Map<Object, Object> cache = new HashMap();
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
//第一步:执行Executor 的 doQuery(),默认是SimpleExecutor
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
//执行查询后,移除占位符
localCache.removeObject(key);
}
//第二步:将查询出来的数据放入一级缓存
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
继续追踪源码,看下doQuery()方法:
//org.apache.ibatis.executor.SimpleExecutor#doQuery
//执行查询
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
//获取到MappedStatement里面的configuration配置信息
Configuration configuration = ms.getConfiguration();
//获取PreparedStatementHandler
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
//获取prepareStatement对象,并且进行参数化.
//也就是将#{id}替换为具体的查询值:1
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
//创建Statement对象
private Statement prepareStatement(StatementHandler handler, Log statementLog) throws SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection, transaction.getTimeout());
//将#{id}替换为具体的查询值:1
handler.parameterize(stmt);
return stmt;
}
//org.apache.ibatis.executor.statement.PreparedStatementHandler#parameterize
public void parameterize(Statement statement) throws SQLException {
//通过parameterHandler参数处理器设置具体的查询参数
parameterHandler.setParameters((PreparedStatement) statement);
}
//org.apache.ibatis.scripting.defaults.DefaultParameterHandler#setParameters
//setParameters方法:替换查询参数为具体的查询值
public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
//拿到boundSql里面的参数映射信息,即id
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
//循环遍历查询参数
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
//属性名称propertyName = id --> select * from user where id = #{id}
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
//根据属性名称id去parameterObject拿到具体查询值
//value = parameterObject.getValue("id") ---> value = 1
value = metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
//真正替换查询参数值
//执行完后:select * from user where id = ? ---> select * from user where id = 1
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (TypeException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
} catch (SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}
前面介绍到了Mybatis在执行之前,将#{id}这些参数替换为具体查询参数值1的过程,这个过程是通过StatementHandler和ParameterHandler完成的。在替换完参数之后,真正到了跟数据库交互的环节了:
//org.apache.ibatis.executor.statement.PreparedStatementHandler#query
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
//第一步:将statement转换成预编译PreparedStatement
PreparedStatement ps = (PreparedStatement) statement;
//第二步:执行具体的查询,这就是原生JDBC实现方式
ps.execute();
//第三步:查询结果处理
return resultSetHandler.handleResultSets(ps);
}
本篇文章详细介绍了mapper方法具体执行流程,其中包括了@Param注解参数的组装、executor、statementHandler等关键对象在查询过程是如何工作的。流程相对复杂,但是我们只需要一步一步调试,观察Mybatis在每个关键步骤的各个属性参数是如何使用的、有什么作用,这样可能会比较好理解一些。
鉴于笔者水平有限,如果文章有什么错误或者需要补充的,希望小伙伴们指出来,希望这篇文章对大家有帮助。