MyBatis整合Spring的实现(11)

前一章节已经介绍了,把方法分解成什么样子来分析,这里先来分析一个方法resultMapElements,在这个方法前还有cacheRefElement与cacheElement,可是因为配置文件中没有配置这2项,因此这里就先跳过。而parameterMapElement在最新的MyBatis中是过期的,也先跳过,之后能够在补充。html

1 配置文件java

<resultMap id="BaseResultMap" type="cn.vansky.schedule.time.menu.bo.Menu">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
      This element was generated on Fri Aug 14 16:08:36 CST 2015.
    -->
    <id column="Id" property="id" jdbcType="INTEGER" />
    <result column="menu_name" property="menuName" jdbcType="VARCHAR" />
    <result column="menu_remark" property="menuRemark" jdbcType="VARCHAR" />
    <result column="menu_parent_id" property="menuParentId" jdbcType="INTEGER" />
    <result column="menu_url" property="menuUrl" jdbcType="VARCHAR" />
    <result column="is_show" property="isShow" jdbcType="TINYINT" />
    <result column="is_delete" property="isDelete" jdbcType="TINYINT" />
    <result column="operation_user_name" property="operationUserName" jdbcType="VARCHAR" />
    <result column="operation_time" property="operationTime" jdbcType="TIMESTAMP" />
  </resultMap>

这里是使用本身扩展MyBatis的自动生成代码,生成的resultMap配置。git

2 代码github

private void resultMapElements(List<XNode> list) throws Exception {
    for (XNode resultMapNode : list) {
      try {
        resultMapElement(resultMapNode);
      } catch (IncompleteElementException e) {
        // ignore, it will be retried
      }
    }
  }
  private ResultMap resultMapElement(XNode resultMapNode) throws Exception {
    return resultMapElement(resultMapNode, Collections.<ResultMapping> emptyList());
}

这里是获取当前文件中全部resultMap对应的XML,而后分别对每一个resultMap进行处理这里会去捕获一个专门的异常,目前还不清楚是起什么做用,先继续往下分析。
3 方法resultMapElementsql

// resultMapNode是对应的resuleMap的XML信息,这里首先获取配置中的id,若是没有就自动生成一个id
// BaseResultMap
String id = resultMapNode.getStringAttribute("id", resultMapNode.getValueBasedIdentifier());
// 那么这行很明显是获取type了,若是没有就获取ofType,尚未就获取resultType,仍是没有就获取javaType
// cn.vansky.schedule.time.menu.bo.Menu
String type = resultMapNode.getStringAttribute("type", 
resultMapNode.getStringAttribute("ofType",
resultMapNode.getStringAttribute("resultType", resultMapNode.getStringAttribute("javaType"))));
// 猜测是获取继承的父类
// null
String extend = resultMapNode.getStringAttribute("extends");
// null
Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
// 获取type对应的Class
Class<?> typeClass = resolveClass(type);
Discriminator discriminator = null;
List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
// 这里additionalResultMappings是空列表,而不是null
resultMappings.addAll(additionalResultMappings);
// 获取子节点id及result
List<XNode> resultChildren = resultMapNode.getChildren();
for (XNode resultChild : resultChildren) {
    if ("constructor".equals(resultChild.getName())) {
        processConstructorElement(resultChild, typeClass, resultMappings);
    } else if ("discriminator".equals(resultChild.getName())) {
        discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
    } else {
        // id与result都走这里
        ArrayList<ResultFlag> flags = new ArrayList<ResultFlag>();
        if ("id".equals(resultChild.getName())) {
          flags.add(ResultFlag.ID);
        }
        resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
    }
}

4 buildResultMappingFromContextmybatis

如下都是以ID为例,进行分析。app

private ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, ArrayList<ResultFlag> flags) throws Exception {
    // id
    String property = context.getStringAttribute("property");
    // Id
    String column = context.getStringAttribute("column");
    // null
    String javaType = context.getStringAttribute("javaType");
    // INTEGER
    String jdbcType = context.getStringAttribute("jdbcType");
    // null
    String nestedSelect = context.getStringAttribute("select");
    // null 
    String nestedResultMap = context.getStringAttribute("resultMap",
        processNestedResultMappings(context, Collections.<ResultMapping> emptyList()));
    // null
    String notNullColumn = context.getStringAttribute("notNullColumn");
    // null
    String columnPrefix = context.getStringAttribute("columnPrefix");
    // null
    String typeHandler = context.getStringAttribute("typeHandler");
    // null
    String resulSet = context.getStringAttribute("resultSet");
    // null
    String foreignColumn = context.getStringAttribute("foreignColumn");
    // false
    boolean lazy = "lazy".equals(context.getStringAttribute("fetchType", configuration.isLazyLoadingEnabled() ? "lazy" : "eager"));
    // null
    Class<?> javaTypeClass = resolveClass(javaType);
    @SuppressWarnings("unchecked")
    // null
    Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
    // 获取到JdbcType
    JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
    // 这里就会构建生成一个ResultMapping
    return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect, nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resulSet, foreignColumn, lazy);
}

5 MapperBuilderAssistant的buildResultMapping方法fetch

public ResultMapping buildResultMapping(
      Class<?> resultType,
      String property,
      String column,
      Class<?> javaType,
      JdbcType jdbcType,
      String nestedSelect,
      String nestedResultMap,
      String notNullColumn,
      String columnPrefix,
      Class<? extends TypeHandler<?>> typeHandler,
      List<ResultFlag> flags,
      String resultSet,
      String foreignColumn, 
      boolean lazy) {
    // 这里若是配置中有javaType属性直接返回,不然经过type配置的类及属性获取对应的Class
    Class<?> javaTypeClass = resolveResultJavaType(resultType, property, javaType);
    // 获取类型处理器 null
    TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);
    // 0
    List<ResultMapping> composites = parseCompositeColumnName(column);
    if (composites.size() > 0) column = null;
    // 初始化一些内部信息
    ResultMapping.Builder builder = new ResultMapping.Builder(configuration, property, column, javaTypeClass);
    builder.jdbcType(jdbcType);
    builder.nestedQueryId(applyCurrentNamespace(nestedSelect, true));
    builder.nestedResultMapId(applyCurrentNamespace(nestedResultMap, true));
    builder.resultSet(resultSet);
    builder.typeHandler(typeHandlerInstance);
    builder.flags(flags == null ? new ArrayList<ResultFlag>() : flags);
    builder.composites(composites);
    builder.notNullColumns(parseMultipleColumnNames(notNullColumn));
    builder.columnPrefix(columnPrefix);
    builder.foreignColumn(foreignColumn);
    builder.lazy(lazy);
    return builder.build();
  }

以上生成的ResultMapping的typeHandler仍是为null的,由于这里获取的是在配置文件中对应的TypeHandler。那么就看一下builder.build()里面是什么代码。ui

public ResultMapping build() {
      // lock down collections
      resultMapping.flags = Collections.unmodifiableList(resultMapping.flags);
      resultMapping.composites = Collections.unmodifiableList(resultMapping.composites);
      resolveTypeHandler();
      validate();
      return resultMapping;
}

原来这里根据配置信息解析出默认使用的TypeHandler,还对一些ResultMapping的信息作了验证,具体代码,自行研究就能够了。
this

6 ResultMapping

6.1 属性

ID最后对应的ResultMapping的信息。

/** 全局配置类 */
private Configuration configuration;
/** id */
private String property;
/** Id */
private String column;
/** java.lang.Integer */
private Class<?> javaType;
/** INTEGER */
private JdbcType jdbcType;
/** IntegerTypeHandler  */
private TypeHandler<?> typeHandler;
/** null */
private String nestedResultMapId;
/** null */
private String nestedQueryId;
/** 空列表 */
private Set<String> notNullColumns;
/** null */
private String columnPrefix;
/** ID */
private List<ResultFlag> flags;
/** 空列表 */
private List<ResultMapping> composites;
/** null */
private String resultSet;
/** null */
private String foreignColumn;
/** false */
private boolean lazy;

menu_name最后对应的ResultMapping的信息。

/** 全局配置类 */
private Configuration configuration;
/** menuName */
private String property;
/** menu_name */
private String column;
/** java.lang.String */
private Class<?> javaType;
/** VARCHAR */
private JdbcType jdbcType;
/** StringTypeHandler */
private TypeHandler<?> typeHandler;
/** null */
private String nestedResultMapId;
/** null */
private String nestedQueryId;
/** 空列表 */
private Set<String> notNullColumns;
/** null */
private String columnPrefix;
/** 空列表 */
private List<ResultFlag> flags;
/** 空列表 */
private List<ResultMapping> composites;
/** null */
private String resultSet;
/** null */
private String foreignColumn;
/** false */
private boolean lazy;

MyBatis的地址http://mybatis.github.io/mybatis-3/zh/sqlmap-xml.html#Result_Maps这里有不少例子,喜欢的童鞋能够多去研究一下。

当对id及result都遍历之后,会生成List<ResultMapping>。

ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
    try {
      return resultMapResolver.resolve();
    } catch (IncompleteElementException  e) {
      configuration.addIncompleteResultMap(resultMapResolver);
      throw e;
    }

若是这里解析失败会抛出前面出现的捕获异常,并把错误的解析放入Configuration(全局配置类)的Collection<ResultMapResolver> incompleteResultMaps = new LinkedList<ResultMapResolver>()。

MapperBuilderAssistant的addResultMap方法

public ResultMap addResultMap(
      String id,
      Class<?> type,
      String extend,
      Discriminator discriminator,
      List<ResultMapping> resultMappings,
      Boolean autoMapping) {
    // 这里把命名空间与id合并
    // cn.vansky.schedule.time.menu.dao.MenuMapper.BaseResultMap
    id = applyCurrentNamespace(id, false);
    // null 
    extend = applyCurrentNamespace(extend, true);
    ResultMap.Builder resultMapBuilder = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping);
    if (extend != null) {
      if (!configuration.hasResultMap(extend)) {
        throw new IncompleteElementException("Could not find a parent resultmap with id '" + extend + "'");
      }
      ResultMap resultMap = configuration.getResultMap(extend);
      List<ResultMapping> extendedResultMappings = new ArrayList<ResultMapping>(resultMap.getResultMappings());
      extendedResultMappings.removeAll(resultMappings);
      // Remove parent constructor if this resultMap declares a constructor.
      boolean declaresConstructor = false;
      for (ResultMapping resultMapping : resultMappings) {
        if (resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR)) {
          declaresConstructor = true;
          break;
        }
      }
      if (declaresConstructor) {
        Iterator<ResultMapping> extendedResultMappingsIter = extendedResultMappings.iterator();
        while (extendedResultMappingsIter.hasNext()) {
          if (extendedResultMappingsIter.next().getFlags().contains(ResultFlag.CONSTRUCTOR)) {
            extendedResultMappingsIter.remove();
          }
        }
      }
      resultMappings.addAll(extendedResultMappings);
    }
    resultMapBuilder.discriminator(discriminator);
    // 这里把新增的ResultMapping作了处理
    ResultMap resultMap = resultMapBuilder.build();
    configuration.addResultMap(resultMap);
    return resultMap;
  }

这里没有具体介绍,还须要慢慢深究。下面来看最终的ResultMap信息。

8 ResultMap属性

// cn.vansky.schedule.time.menu.dao.MenuMapper.BaseResultMap
private String id;
// cn.vansky.schedule.time.menu.bo.Menu
private Class<?> type;
// 对应配置中的全部结果列,这里9个对象
private List<ResultMapping> resultMappings;
// 对应配置中的id列,这里1个对象
private List<ResultMapping> idResultMappings;
// 对应构造器的列,这里为0个对象
private List<ResultMapping> constructorResultMappings;
// 看代码得出,只要不是构造器列,就属于这里,也就是包括id和result
private List<ResultMapping> propertyResultMappings;
// 对应的配置的列名所有大写,这里使用的set因此也就不是按顺序来排列的了
// MENU_PARENT_ID,MENU_NAME,MENU_URL,OPERATION_TIME,IS_SHOW,OPERATION_USER_NAME,ID,IS_DELETE,MENU_REMARK
private Set<String> mappedColumns;
// null
private Discriminator discriminator;
// false
private boolean hasNestedResultMaps;
// false
private boolean hasNestedQueries;
// null
private Boolean autoMapping;

至此最终的ResultMap信息出来了。

总结:

这里不少东西,做者也是一点一点去研究,并且实际项目中的配置也不是特别的多,因此有些还待完善。

相关文章
相关标签/搜索