Mybatis的resultMap里的column属性为何不能使用“表名.字段名”的形式

背景

最近朋友问了我一个问题:Mybatis的resultMap里面的column属性为什么不能使用类似c.id这样的形式而要使用别名。
图1.png

我先是查找了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")是否能够拿到相应字段的值。

图2.png

测试结果是可以拿到!也就是说,在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)这行代码,所以该值为空。

分析过程

  1. 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对象中进行缓存。

  1. 查询后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的内容进行比对,肯定就是寄了。

  1. 查询后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字段无法使用“表名.字段名”这种形式。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,000评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,745评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,561评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,782评论 1 298
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,798评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,394评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,952评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,852评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,409评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,483评论 3 341
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,615评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,303评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,979评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,470评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,571评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,041评论 3 377
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,630评论 2 359

推荐阅读更多精彩内容