经过上一篇的getMapper方法的讲解之后getMapper解析。
此时Mybatis已经通过动态代理,创建了Dao的具体对象。因为其中MapperProxy实现了InvocationHandler,所以在执行具体的方法时,会执行MapperProxy中的invoke方法。
test方法
前几篇文章中已经解析到了getMapper方法,所以本篇会针对具体方法继续向下进行解析。
public void test02() {
// 根据全局配置文件创建出SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
//加载mybatis-config.xml并转换为Stream流
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
// SqlSessionFactory:负责创建SqlSession对象的工厂
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// SqlSession:表示跟数据库建议的一次会话
// 获取数据库的会话,创建出数据库连接的会话对象(事务工厂,事务对象,执行器,如果有插件的话会进行插件的解析)
SqlSession sqlSession = sqlSessionFactory.openSession();
Emp empByEmpno = null;
try {
// 获取要调用的接口类,创建出对应的mapper的动态代理对象(mapperRegistry.knownMapper)
EmpDao mapper = sqlSession.getMapper(EmpDao.class);
// 调用方法开始执行
empByEmpno = mapper.findEmpByEmpnoAndEname(7369, "SMITH");
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
System.out.println(empByEmpno);
}
invoke
前面已经提到,因为MapperProxy实现了InvocationHandler,所以在执行具体的方法时,会执行MapperProxy中的invoke方法。
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -4724728412955527868L;
private static final int ALLOWED_MODES = MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
| MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC;
private static final Constructor<Lookup> lookupConstructor;
private static final Method privateLookupInMethod;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
//用于缓存MapperMethod对象(其中属性包含SqlCommand和MethodSignature),其中key是mapper接口中方法对应的Method对象,value是MapperMethod对象
//MapperMethod对象会完成参数转换,以及SQL语句的执行功能,需要注意的是,MapperMethod中并不记录任何状态相关的信息,所以可以在多个代理对象之间共享
private final Map<Method, MapperMethodInvoker> methodCache;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//如果目标方法继承自Object,则直接调用该方法
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else {
//根据被调用接口方法的method对象,从缓存中获取MapperMethodInvoker对象,如果没有则创建一个并放入缓存,执行invoke方法。
return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
}
// 省略部分代码。。。。
cachedInvoker
因为是普通的接口方法,所以会执行cachedInvoker方法,将method放入methodCache缓存中。
private MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
try {
//如果能够在methodCache(Map<Method, MapperMethodInvoker>)中,根据method(key)找到value,则返回,找不到,就加到methodCache中
//会执行ConcurrentHashMap的computeIfAbsent方法 ->
// MapperProxyFactory加载时private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();
return MapUtil.computeIfAbsent(methodCache, method, m -> {
//因为JDK1.8新特性,允许接口中有方法的具体实现(default修饰),所以在此处做判断,看要执行的方法是否是接口中的实现方法。
//如果是接口中的实现方法会走下面的逻辑
if (m.isDefault()) {
try {
if (privateLookupInMethod == null) {
//根据JDK8和JDK9做了不同的操作
return new DefaultMethodInvoker(getMethodHandleJava8(method));
} else {
return new DefaultMethodInvoker(getMethodHandleJava9(method));
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
throw new RuntimeException(e);
}
} else {
//普通的接口方法
return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
});
} catch (RuntimeException re) {
Throwable cause = re.getCause();
throw cause == null ? re : cause;
}
}
MapperMethod
如果是普通的接口方法,则先会根据mapperInterface, method和Configuration构建MapperMethod。
包含了要执行的具体sql,方法参数、返回值等。。。
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
this.command = new SqlCommand(config, mapperInterface, method);
this.method = new MethodSignature(config, mapperInterface, method);
}
SqlCommand
构造sqlCommand,根据接口名+方法名,获取MapperStatement对象,
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) {
//获取方法名
final String methodName = method.getName();
//Dao接口对象
final Class<?> declaringClass = method.getDeclaringClass();
MappedStatement ms = resolveMappedStatement(mapperInterface, methodName, declaringClass,
configuration);
//处理Flush注解
if (ms == null) {
if (method.getAnnotation(Flush.class) != null) {
name = null;
type = SqlCommandType.FLUSH;
} else {
throw new BindingException("Invalid bound statement (not found): "
+ mapperInterface.getName() + "." + methodName);
}
} else {
//接口全限定名+方法名
name = ms.getId();
//操作类型 select、insert、update。。。
type = ms.getSqlCommandType();
//如果type是unknown类型,抛异常
if (type == SqlCommandType.UNKNOWN) {
throw new BindingException("Unknown execution method for: " + name);
}
}
}
resolveMappedStatement
private MappedStatement resolveMappedStatement(Class<?> mapperInterface, String methodName,
Class<?> declaringClass, Configuration configuration) {
//接口名+方法名拼接的id
String statementId = mapperInterface.getName() + "." + methodName;
//因为之前解析时,MapperStatement中解析了mapper.xml所有属性节点。
//configuration中的MapperStatement中是否包含当前的接口名+方法名。
//所以,要想执行具体的SQL语句,就要根据statementId获取到mapperStatement对象
if (configuration.hasStatement(statementId)) {
return configuration.getMappedStatement(statementId);
} else if (mapperInterface.equals(declaringClass)) {
return null;
}
//下面方法是不是永远走不到? 上面不管statementId是否为null,都会进行返回
for (Class<?> superInterface : mapperInterface.getInterfaces()) {
if (declaringClass.isAssignableFrom(superInterface)) {
MappedStatement ms = resolveMappedStatement(superInterface, methodName,
declaringClass, configuration);
if (ms != null) {
return ms;
}
}
}
return null;
}
MethodSignature
类名可以翻译为方法签名,获取返回类型
public MethodSignature(Configuration configuration, Class<?> mapperInterface, Method method) {
//解析方法返回值类型
Type resolvedReturnType = TypeParameterResolver.resolveReturnType(method, mapperInterface);
if (resolvedReturnType instanceof Class<?>) {
this.returnType = (Class<?>) resolvedReturnType;
} else if (resolvedReturnType instanceof ParameterizedType) {
this.returnType = (Class<?>) ((ParameterizedType) resolvedReturnType).getRawType();
} else {
this.returnType = method.getReturnType();
}
//根据返回类型初始化returnsVoid、returnsMany、returnsCursor、returnsOptional等参数
this.returnsVoid = void.class.equals(this.returnType);
this.returnsMany = configuration.getObjectFactory().isCollection(this.returnType) || this.returnType.isArray();
this.returnsCursor = Cursor.class.equals(this.returnType);
this.returnsOptional = Optional.class.equals(this.returnType);
// 若MethodSignature对应方法的返回值是Map且制定了@MapKey注解,则使用getMapKey方法处理
this.mapKey = getMapKey(method);
this.returnsMap = this.mapKey != null;
// 初始化rowBoundsIndex、resultHandlerIndex字段
this.rowBoundsIndex = getUniqueParamIndex(method, RowBounds.class);
this.resultHandlerIndex = getUniqueParamIndex(method, ResultHandler.class);
// 创建ParamNameResolver对象
this.paramNameResolver = new ParamNameResolver(configuration, method);
}
ParamNameResolver
参数解析、映射
public ParamNameResolver(Configuration config, Method method) {
this.useActualParamName = config.isUseActualParamName();
//获取参数列表中每个参数的类型
final Class<?>[] paramTypes = method.getParameterTypes();
//获取到注解
final Annotation[][] paramAnnotations = method.getParameterAnnotations();
//记录参数索引和参数名的对应关系
final SortedMap<Integer, String> map = new TreeMap<>();
int paramCount = paramAnnotations.length;
//遍历所有注解
for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
//
if (isSpecialParameter(paramTypes[paramIndex])) {
// skip special parameters
// 如果参数是RowBounds类型或ResultHandler类型,则跳过对该参数的分析
continue;
}
String name = null;
//遍历注解
for (Annotation annotation : paramAnnotations[paramIndex]) {
if (annotation instanceof Param) {
hasParamAnnotation = true;
// 获取@Param注解指定的参数名称
name = ((Param) annotation).value();
break;
}
}
if (name == null) {
// @Param was not specified.
// 该参数没有对应的@Param注解,则根据配置决定是否使用参数实际名称作为其名称
if (useActualParamName) {
name = getActualParamName(method, paramIndex);
}
if (name == null) {
// use the parameter index as the name ("0", "1", ...)
// gcode issue #71
// 使用参数的索引作为其名称 arg0,arg1
name = String.valueOf(map.size());
}
}
// 记录到map中保存
map.put(paramIndex, name);
}
// 初始化name集合
names = Collections.unmodifiableSortedMap(map);
}
再次回到cachedInvoker方法,因为第一次进来methodCache(Map<Method, MapperMethodInvoker>)中为该method的key为null,所以会执行上面的操作,当上面的操作执行完后,methodCache中就已经有Method的键值对了。而后,会执行MapperProxy中的invoke方法,来执行SQL的查询。
MapperProxy
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static class PlainMethodInvoker implements MapperMethodInvoker {
private final MapperMethod mapperMethod;
public PlainMethodInvoker(MapperMethod mapperMethod) {
super();
this.mapperMethod = mapperMethod;
}
//省略部分代码。。。。
@Override
public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
return mapperMethod.execute(sqlSession, args);
}
}
}
execute
根据SQL的命令类型,来执行具体的查询
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:
//处理返回值是Void并且ResultSet通过ResultHandler处理的方法
if (method.returnsVoid() && method.hasResultHandler()) {
//如果有结果处理器(ResultHandler)
executeWithResultHandler(sqlSession, args);
result = null;
//是否返回多条记录
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
//是否返回Map类型
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
//返回cursor
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
//返回单一对象的处理办法
} else {
//得到实参和参数名的映射
Object param = method.convertArgsToSqlCommandParam(args);
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;
}
convertArgsToSqlCommandParam
获取到实参,并进行map映射
public Object convertArgsToSqlCommandParam(Object[] args) {
return paramNameResolver.getNamedParams(args);
}
public Object getNamedParams(Object[] args) {
final int paramCount = names.size();
//没有参数,返回null
if (args == null || paramCount == 0) {
return null;
//没使用Param注解且只有一个参数
} else if (!hasParamAnnotation && paramCount == 1) {
Object value = args[names.firstKey()];
return wrapToMapIfCollection(value, useActualParamName ? names.get(0) : null);
} else {
//处理使用@Param注解指定了参数名称或者多个参数
final Map<String, Object> param = new ParamMap<>();
int i = 0;
//names是索引为key,参数名称为value的Map结构
for (Map.Entry<Integer, String> entry : names.entrySet()) {
//ParamMap记录了参数名称和实际参数的关系,继承了HashMap,不允许Key相同。
param.put(entry.getValue(), args[entry.getKey()]);
//生成param1、param2的参数形式
final String genericParamName = GENERIC_NAME_PREFIX + (i + 1);
// 如果names的map中,key也是以param1方式命名,则不添加,否则将param1的形式也添加到paramMap中
if (!names.containsValue(genericParamName)) {
param.put(genericParamName, args[entry.getKey()]);
}
i++;
}
return param;
}
}
selectOne
针对返回单一数据的查询
@Override
public <T> T selectOne(String statement, Object parameter) {
// 还是调用selectList方法
List<T> list = this.selectList(statement, parameter);
//返回list0
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 {
//没有则返回null
return null;
}
}
public <E> List<E> selectList(String statement, Object parameter) {
//RowBounds.DEFAULT使用默认分页
return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
selectList
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
//从Configuration中获取MappedStatement,包含sql语句
MappedStatement ms = configuration.getMappedStatement(statement);
//使用执行器来查询结果,handler是个null
//wrapCollection(parameter)获取到参数
return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
query
执行具体查询
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
//获取BoundSql对象,里面包含SQL、形参和实参
BoundSql boundSql = ms.getBoundSql(parameterObject);
//创建CacheKey
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
createCacheKey
根据id、偏移量、limit等设置cacheKey
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
//Executor,默认SIMPLE,根据delegate创建缓存对象
return delegate.createCacheKey(ms, parameterObject, rowBounds, boundSql);
}
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
//看当前Executor是否关闭
if (closed) {
throw new ExecutorException("Executor was closed.");
}
CacheKey cacheKey = new CacheKey();
//将msId添加进cacheKey中 -> 接口全限定名+方法名
cacheKey.update(ms.getId());
cacheKey.update(rowBounds.getOffset());
//将limit放到cacheKey中
cacheKey.update(rowBounds.getLimit());
//将sql放到cacheKey中
cacheKey.update(boundSql.getSql());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
// mimic DefaultParameterHandler logic
//获取传入的实参,放到cacheKey中
for (ParameterMapping parameterMapping : parameterMappings) {
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
//将实参添加到cacheKey中
cacheKey.update(value);
}
}
if (configuration.getEnvironment() != null) {
// issue #176
cacheKey.update(configuration.getEnvironment().getId());
}
return cacheKey;
}
query
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.");
}
//queryStack 查询栈
if (queryStack == 0 && ms.isFlushCacheRequired()) {
//嵌套查询,并且select节点配置的flushCache属性为true时,才会清空一级缓存,flushCache配置项是影响一级缓存中结果对象存活时长的第一个方面
clearLocalCache();
}
List<E> list;
try {
//栈++
queryStack++;
//查询一级缓存,key为cacheKey
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
//一级缓存为null,从数据库中查询
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;
}
queryFromDatabase
一级缓存为null,从数据库查询
// 从数据库查
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
// 在缓存中添加占位符
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
// 完成数据库查询操作,并返回结果对象
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
获取Statement对象,创建StatementHandler,调用handler执行查询
@Override
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对象,实际返回的是RoutingStatementHandler对象
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
// 完成Statement的创建和初始化
stmt = prepareStatement(handler, ms.getStatementLog());
// 调用query方法执行sql语句,并通过ResultSetHandler完成结果集的映射
return handler.query(stmt, resultHandler);
} finally {
// 关闭Statement对象
closeStatement(stmt);
}
}
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
// 获取SQL语句
String sql = boundSql.getSql();
// 执行SQL语句
statement.execute(sql);
// 映射结果集
return resultSetHandler.handleResultSets(statement);
}
handleResultSets
将查询后返回的结果集做映射处理文章来源:https://www.toymoban.com/news/detail-426817.html
public List<Object> handleResultSets(Statement stmt) throws SQLException {
ErrorContext.instance().activity("handling results").object(mappedStatement.getId());
// 该集合用于保存映射结果得到的结果对象
final List<Object> multipleResults = new ArrayList<>();
int resultSetCount = 0;
// 获取第一个ResultSet对象
ResultSetWrapper rsw = getFirstResultSet(stmt);
// 获取MappedStatement.resultMaps集合
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
int resultMapCount = resultMaps.size();
// 如果集合集不为空,则resultMaps集合不能为空,否则抛出异常
validateResultMapsCount(rsw, resultMapCount);
// 遍历resultMaps集合
while (rsw != null && resultMapCount > resultSetCount) {
// 获取该结果集对应的ResultMap对象
ResultMap resultMap = resultMaps.get(resultSetCount);
// 根据ResultMap中定义的映射规则对ResultSet进行映射,并将映射的结果对象添加到multipleResult集合中保存
handleResultSet(rsw, resultMap, multipleResults, null);
// 获取下一个结果集
rsw = getNextResultSet(stmt);
// 清空nestedResultObjects集合
cleanUpAfterHandlingResultSet();
// 递增resultSetCount
resultSetCount++;
}
// 获取MappedStatement.resultSets属性,该属性对多结果集的情况使用,该属性将列出语句执行后返回的结果集,并给每个结果集一个名称,名称是逗号分隔的,
String[] resultSets = mappedStatement.getResultSets();
if (resultSets != null) {
while (rsw != null && resultSetCount < resultSets.length) {
// 根据resultSet的名称,获取未处理的ResultMapping
ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]);
if (parentMapping != null) {
String nestedResultMapId = parentMapping.getNestedResultMapId();
ResultMap resultMap = configuration.getResultMap(nestedResultMapId);
// 根据ResultMap对象映射结果集
handleResultSet(rsw, resultMap, null, parentMapping);
}
// 获取下一个结果集
rsw = getNextResultSet(stmt);
// 清空nestedResultObjects集合
cleanUpAfterHandlingResultSet();
// 递增resultSetCount
resultSetCount++;
}
}
return collapseSingleResultList(multipleResults);
}
整体执行流程
查询流程
文章来源地址https://www.toymoban.com/news/detail-426817.html
到了这里,关于Mybatis源码(四)— 查询流程的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!