背景
最近朋友问了我一个问题:Mybatis的resultMap里面的column属性为什么不能使用类似c.id这样的形式而要使用别名。我先是查找了Mybatis的文档,找到了一句column属性的介绍:
column
The column name from the database, or the aliased column label. This is the same string that would normally be passed to resultSet.getString(columnName).
翻译:数据库中的列名,或别名列标签。 这与通常传递给resultSet.getString(columnName)的字符串相同。
既然说是与通常传递给resultSet.getString(columnName)
的字符串相同,那我自然是先去测试一下在JDBC中直接使用resultSet.getString("c.id")
是否能够拿到相应字段的值。
测试结果是可以拿到!也就是说,在Mybatis把column字段传给
resultSet.getString()
之前,还进行了一些别的操作,导致使用"c.id"这样形式无法获取值。
Mybatis版本
org.mybatis:mybatis:3.5.9
结论
先说结论,后面再写分析过程。
首先,XML文件中定义的resultMap块在代码中对应的是org.apache.ibatis.mapping.ResultMap对象,里面存放的column字段未进行任何处理,即填写的是"c.id",则里面存放的也是"c.id"。
然后,查询结果ResultSet的相关信息如字段名、类型等信息则存放在org.apache.ibatis.executor.resultset.ResultSetWrapper对象中,该对象中的字段名称列表List<String> columnNames
保存的是resultSet的字段的别名或原名(优先别名),即如果SQL中的SELECT块中写的是c.id AS c_id
,则columnNames存放的是"c_id",如果没定义别名,则存放的是"id"。
接着,将查询结果的字段放入相应对象的过程中,有一段代码对ResultMapping的column和ResultSetWrapper的columnName进行了比较判断,即仅当两个对象中的column相互对应时才会将结果放入,否则将跳过该字段。
最后,因为"c.id"与"id"不对应,该字段被跳过,所以相应字段根本没走到resultSet.getString(columnName)
这行代码,所以该值为空。
分析过程
- Mybatis读取XML文件中resultMap块的处理过程。
经过debug查看,resultMap块的每个字段在org.apache.ibatis.builder.xml.XMLMapperBuilder#buildResultMappingFromContext方法中被初始化为ResultMapping对象。
private ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, List<ResultFlag> flags) {
String property;
if (flags.contains(ResultFlag.CONSTRUCTOR)) {
property = context.getStringAttribute("name");
} else {
property = context.getStringAttribute("property");
}
String column = context.getStringAttribute("column");
String javaType = context.getStringAttribute("javaType");
String jdbcType = context.getStringAttribute("jdbcType");
String nestedSelect = context.getStringAttribute("select");
String nestedResultMap = context.getStringAttribute("resultMap", () ->
processNestedResultMappings(context, Collections.emptyList(), resultType));
String notNullColumn = context.getStringAttribute("notNullColumn");
String columnPrefix = context.getStringAttribute("columnPrefix");
String typeHandler = context.getStringAttribute("typeHandler");
String resultSet = context.getStringAttribute("resultSet");
String foreignColumn = context.getStringAttribute("foreignColumn");
boolean lazy = "lazy".equals(context.getStringAttribute("fetchType", configuration.isLazyLoadingEnabled() ? "lazy" : "eager"));
Class<?> javaTypeClass = resolveClass(javaType);
Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect, nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resultSet, foreignColumn, lazy);
}
这里我比较关注的column字段没有进行任何处理,直接放入了ResultMapping对象中,然后ResultMapping被放入ResultMap对象中。初始化后的ResultMap被放入全局的org.apache.ibatis.session.Configuration对象中进行缓存。
- 查询后Mybatis对数据库返回内容的处理方法。
经过debug查看,进行参数映射处理的方法是org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyPropertyMappings,下面是这个方法的签名。
private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix)
throws SQLException {
...
}
这个方法的参数需要关注的是ResultSetWrapper和ResultMap。ResultMap对象是XML中定义的resultMap的信息,对象里面保存了ResultMapping对象列表,这个列表的初始化过程前面已经看过了,现在来看一下ResultSetWrapper这个对象。
public class ResultSetWrapper {
private final ResultSet resultSet;
private final TypeHandlerRegistry typeHandlerRegistry;
private final List<String> columnNames = new ArrayList<>();
private final List<String> classNames = new ArrayList<>();
private final List<JdbcType> jdbcTypes = new ArrayList<>();
private final Map<String, Map<Class<?>, TypeHandler<?>>> typeHandlerMap = new HashMap<>();
private final Map<String, List<String>> mappedColumnNamesMap = new HashMap<>();
private final Map<String, List<String>> unMappedColumnNamesMap = new HashMap<>();
public ResultSetWrapper(ResultSet rs, Configuration configuration) throws SQLException {
super();
this.typeHandlerRegistry = configuration.getTypeHandlerRegistry();
this.resultSet = rs;
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add(configuration.isUseColumnLabel() ? metaData.getColumnLabel(i) : metaData.getColumnName(i));
jdbcTypes.add(JdbcType.forCode(metaData.getColumnType(i)));
classNames.add(metaData.getColumnClassName(i));
}
}
...
}
从类名上看,这个类是对ResultSet的一个包装,里面缓存了一些字段类型和映射等信息,ResultSet是JDBC进行数据库查询后返回的结果集对象。
这里我比较关注的是columnNames这个List,我排查到这里的时候就感觉应该是columnName和ResultMap的column对不上的问题。初始化方法里面的for循环里的第一行可以看到,columnNames中存放的内容是ResultSet中字段的别名或原名,所以如果用这个List里面的内容和ResultMap的内容进行比对,肯定就是寄了。
- 查询后Mybatis对数据库返回内容的处理过程。
然后我们继续看看org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyPropertyMappings这个字段映射处理方法的逻辑。
private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix)
throws SQLException {
final List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
boolean foundValues = false;
final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
for (ResultMapping propertyMapping : propertyMappings) {
String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
if (propertyMapping.getNestedResultMapId() != null) {
// the user added a column attribute to a nested result map, ignore it
column = null;
}
if (propertyMapping.isCompositeResult()
|| (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH)))
|| propertyMapping.getResultSet() != null) {
Object value = getPropertyMappingValue(rsw.getResultSet(), metaObject, propertyMapping, lazyLoader, columnPrefix);
// issue #541 make property optional
final String property = propertyMapping.getProperty();
if (property == null) {
continue;
} else if (value == DEFERRED) {
foundValues = true;
continue;
}
if (value != null) {
foundValues = true;
}
if (value != null || (configuration.isCallSettersOnNulls() && !metaObject.getSetterType(property).isPrimitive())) {
// gcode issue #377, call setter on nulls (value is not 'found')
metaObject.setValue(property, value);
}
}
}
return foundValues;
}
方法的第一行是获取ResultSetWrapper里面缓存的mappedColumnNames列表,直接来看一下加载缓存的方法org.apache.ibatis.executor.resultset.ResultSetWrapper#loadMappedAndUnmappedColumnNames。
private void loadMappedAndUnmappedColumnNames(ResultMap resultMap, String columnPrefix) throws SQLException {
List<String> mappedColumnNames = new ArrayList<>();
List<String> unmappedColumnNames = new ArrayList<>();
final String upperColumnPrefix = columnPrefix == null ? null : columnPrefix.toUpperCase(Locale.ENGLISH);
final Set<String> mappedColumns = prependPrefixes(resultMap.getMappedColumns(), upperColumnPrefix);
for (String columnName : columnNames) {
final String upperColumnName = columnName.toUpperCase(Locale.ENGLISH);
if (mappedColumns.contains(upperColumnName)) {
mappedColumnNames.add(upperColumnName);
} else {
unmappedColumnNames.add(columnName);
}
}
mappedColumnNamesMap.put(getMapKey(resultMap, columnPrefix), mappedColumnNames);
unMappedColumnNamesMap.put(getMapKey(resultMap, columnPrefix), unmappedColumnNames);
}
这个方法中的for循环是用columnNames这个列表的内容与ResultMap的column列表进行匹配,只有ResultMap中存在的字段才会被放入mappedColumnNames。而从前面的columnNames初始化过程可以知道,columnNames是字段的别名或原名,所以如果resultMap中没有定义"id"这个字段,这个列表就不会包含"id","c.id"就已经匹配不到相应的字段了,不过开头的例子在这里还没有遇到这个情况。
然后再回到org.apache.ibatis.executor.resultset.DefaultResultSetHandler#applyPropertyMappings,第一行获取到的列表其实已经进行了一次对字段映射的筛选,即ResultMap中没有定义的字段都忽略掉。接着的是一个for循环,对ResultMap的字段进行遍历,中间的一个if又进行了第二次的columnName的判断mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))
,即只有第一行获取的mappedColumnNames列表中存在的字段才会通过,否则将会被跳过,而mappedColumnNames列表中只可能存在字段的别名或原名,所以"c.id"无法通过这条判断,寄。
然而这个if语句中的第一行就是被层层嵌套的resultSet.getString(columnName)
,也就是说"c.id"倒在了终点前,泪目。
总结
从前面的分析中可以发现,column在到达resultSet.getString(columnName)
之前经历了两次过滤,目的是让ResultMap和ResultSet中的字段一一对应,而由于ResultSetWrapper只取字段别名或原名,导致“表名.字段名”这种形式无法通过这两次过滤,所以column字段无法使用“表名.字段名”这种形式。