mybatis配置加载阶段源码之XMLMapperBuilder

作用

主要负责解析*Mpper.xml映射文件。

构造方法

XMLMapperBuilder 也是同样继承于BaseBuilder,它有以下四个构造方法,最终调用的还是最后一个构造方法来初始化XMLMapperBuilder 对象。

@Deprecated
  public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, Map<String, XNode> sqlFragments, String namespace) {
    this(reader, configuration, resource, sqlFragments);
    this.builderAssistant.setCurrentNamespace(namespace);
  }

  @Deprecated
  public XMLMapperBuilder(Reader reader, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {
    this(new XPathParser(reader, true, configuration.getVariables(), new XMLMapperEntityResolver()),
        configuration, resource, sqlFragments);
  }

  public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource, Map<String, XNode> sqlFragments, String namespace) {
    this(inputStream, configuration, resource, sqlFragments);
    this.builderAssistant.setCurrentNamespace(namespace);
  }

  public XMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {
    this(new XPathParser(inputStream, true, configuration.getVariables(), new XMLMapperEntityResolver()),
        configuration, resource, sqlFragments);
  }

XMLMapperBuilder 对象的创建是在XMLConfigBuilder#mapperElement方法中

if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            try(InputStream inputStream = Resources.getResourceAsStream(resource)) {
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
              mapperParser.parse();
            }
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            try(InputStream inputStream = Resources.getUrlAsStream(url)){
              XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
              mapperParser.parse();
            }
          } 

方法

parse

parse方法是*Mapper.xml 解析的开始

public void parse() {
    //判断是否已经加载该配置文件
    if (!configuration.isResourceLoaded(resource)) {
      //处理mapper节点
      configurationElement(parser.evalNode("/mapper"));
      //将mapper文件添加到configuration.loadedResources中
      configuration.addLoadedResource(resource);
      //注册mapper接口
      bindMapperForNamespace();
    }
    //处理解析失败的ResultMap节点
    parsePendingResultMaps();
    //处理解析失败的CacheRef节点
    parsePendingCacheRefs();
    //处理解析失败的Sql语句节点
    parsePendingStatements();
  }

解析步骤分两种情况:
一、资源已加载
如果资源已加载就直接处理失败的节点,这一步比较简单。
二、资源未加载
如果资源未加载,分四个步骤:
1、解析mapper标签
2、资源加载到configuration对象的loadedResources的set集合中
3、注册mapper接口
4、处理解析失败的节点

configurationElement

1、解析mapper标签
mapper的解析在configurationElement方法中,在该方法中会对*Mapper.xml内的节点进行解析并将解析到的结果填充到configuration对象中。

/**
   *  解析*mapper.xml文件
   * @param context
   */
  private void configurationElement(XNode context) {
    try {
      String namespace = context.getStringAttribute("namespace");
      if (namespace == null || namespace.isEmpty()) {
        throw new BuilderException("Mapper's namespace cannot be empty");
      }
      // 设置当前命名空间
      builderAssistant.setCurrentNamespace(namespace);
      // 缓存解析
      cacheRefElement(context.evalNode("cache-ref"));
      cacheElement(context.evalNode("cache"));

      // parameterMap 标签已过时
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));

      // 解析resultMap
      resultMapElements(context.evalNodes("/mapper/resultMap"));
      sqlElement(context.evalNodes("/mapper/sql"));
      buildStatementFromContext(context.evalNodes("select|insert|update|delete"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing Mapper XML. The XML location is '" + resource + "'. Cause: " + e, e);
    }
  }

标签

映射文件各个标签具体介绍可看官网XML 映射器,这里只关注几个重要的节点

resultMap

resultMap节点的解析是在resultMapElements方法中进行的,经过层层调用最终调用
ResultMap resultMapElement(XNode resultMapNode, List additionalResultMappings, Class<?> enclosingType) 方法,重点要看的就是这个方法

resultMapElements

private void resultMapElements(List<XNode> list) {
    for (XNode resultMapNode : list) {
      try {
        resultMapElement(resultMapNode);
      } catch (IncompleteElementException e) {
        // ignore, it will be retried
      }
    }
  }

resultMapElement

private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings, Class<?> enclosingType) {
    ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());

    /**
     * 获取resultMap 映射的类
     * javaType、resultType、ofType、type 优先级顺序是
     * type > ofType > resultType >javaType,
     * 解析的时候按先从优先级最低的javaType属性开始,type的优先级最高,只要type属性存在,不管其他三个有没有最终都会用type,
     * 如果type属性没有获取到才会按照顺序依次往下获取并使用结果
     */
    String javaType = resultMapNode.getStringAttribute("javaType");
    String resultType = resultMapNode.getStringAttribute("resultType", javaType);
    String ofType = resultMapNode.getStringAttribute("ofType", resultType);
    String type = resultMapNode.getStringAttribute("type", ofType);

    // 从别名注册表中获取entity 的class对象
    Class<?> typeClass = resolveClass(type);
    if (typeClass == null) {
      // 别名注册中如果没找到entity的class对象,
      typeClass = inheritEnclosingType(resultMapNode, enclosingType);
    }

    Discriminator discriminator = null;
    List<ResultMapping> resultMappings = new ArrayList<>(additionalResultMappings);
    List<XNode> resultChildren = resultMapNode.getChildren();
    for (XNode resultChild : resultChildren) {
      if ("constructor".equals(resultChild.getName())) {
        //constructor 节点解析
        processConstructorElement(resultChild, typeClass, resultMappings);
      } else if ("discriminator".equals(resultChild.getName())) {
        //discriminator 节点解析
        discriminator = processDiscriminatorElement(resultChild, typeClass, resultMappings);
      } else {
        List<ResultFlag> flags = new ArrayList<>();
        if ("id".equals(resultChild.getName())) {
          // 将id节点添加到ResultFlag 集合中
          flags.add(ResultFlag.ID);
        }
        // 创建resultMapping对象并加入到resultMappings 集合中
        resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
      }
    }

    //获取基于值的标识符  拼接成mapper_resultMap[BaseResultMap] 这样的字段,mapper 代表文件夹名, [ ]中间是resultMap节点的id属性值,这里id=BaseResultMap
    String valueBasedIdentifier = resultMapNode.getValueBasedIdentifier();
    String id = resultMapNode.getStringAttribute("id", valueBasedIdentifier);
    String extend = resultMapNode.getStringAttribute("extends");
    Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
    // resultMap解析器
    ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
    try {
      // 返回resultMap对象
      return resultMapResolver.resolve();
    } catch (IncompleteElementException e) {
      configuration.addIncompleteResultMap(resultMapResolver);
      throw e;
    }
  }

解析步骤:
1、解析resultMap节点的属性找到映射类并从typeAliasRegistry类型别名注册表中找到对应的映射类的class对象。
2、循环解析resultMap的子节点。
2.1 解析constructor节点,解析步骤在processConstructorElement方法中。解析调用ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, List flags)方法。

/**
   * constructor节点解析
   * @param resultChild 节点
   * @param resultType 映射类
   * @param resultMappings ResultMapping结果映射集合
   */
  private void processConstructorElement(XNode resultChild, Class<?> resultType, List<ResultMapping> resultMappings) {
    List<XNode> argChildren = resultChild.getChildren();
    for (XNode argChild : argChildren) {
      List<ResultFlag> flags = new ArrayList<>();
      flags.add(ResultFlag.CONSTRUCTOR);
      // idArg 类的id属性
      if ("idArg".equals(argChild.getName())) {
        flags.add(ResultFlag.ID);
      }
      resultMappings.add(buildResultMappingFromContext(argChild, resultType, flags));
    }
  }

2.2 解析discriminator节点,解析步骤在processDiscriminatorElement方法中。discriminator鉴别器会根据value的结果值来决定最终调用哪个resultMap。

private Discriminator processDiscriminatorElement(XNode context, Class<?> resultType, List<ResultMapping> resultMappings) {
    String column = context.getStringAttribute("column");
    String javaType = context.getStringAttribute("javaType");
    String jdbcType = context.getStringAttribute("jdbcType");
    String typeHandler = context.getStringAttribute("typeHandler");
    Class<?> javaTypeClass = resolveClass(javaType);
    Class<? extends TypeHandler<?>> typeHandlerClass = resolveClass(typeHandler);
    JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
    Map<String, String> discriminatorMap = new HashMap<>();
    for (XNode caseChild : context.getChildren()) {
      // 取值
      String value = caseChild.getStringAttribute("value");
      // 获取嵌套的resultMap节点 id属性
      String resultMap = caseChild.getStringAttribute("resultMap", processNestedResultMappings(caseChild, resultMappings, resultType));
      // 根据结果获取对应的resultMap
      discriminatorMap.put(value, resultMap);
    }
    // 构建一个Discriminator 对象返回
    return builderAssistant.buildDiscriminator(resultType, column, javaTypeClass, jdbcTypeEnum, typeHandlerClass, discriminatorMap);
  }

2.3 解析其他节点,其他节点的解析步骤在buildResultMappingFromContext方法中

/**
   *  解析 result 节点 并封装为ResultMapping 返回
   * @param context
   * @param resultType
   * @param flags
   * @return
   */
  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 枚举类型获取
    JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
    // 创建resultMapping对象
    return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect, nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resultSet, foreignColumn, lazy);
  }

3、解析resultMap节点的id、extends、autoMapping等属性,然后构建一个ResultMapResolver
4、调用ResultMapResolver对象的resolve方法,解析并返回一个resultMap对象。resolve方法会调用MapperBuilderAssistant#addResultMap方法把解析到各种参数设值到resultMap对象中并返回,实际设值的方法是ResultMap#build方法,build方法中就是对ResultMap属性的各种赋值。
MapperBuilderAssistant#addResultMap

public ResultMap addResultMap(String id, Class<?> type,String extend, Discriminator discriminator, List<ResultMapping> resultMappings, Boolean autoMapping) {
    id = applyCurrentNamespace(id, false);
    extend = applyCurrentNamespace(extend, true);

    // 如果resultMap有继承一个resultMap,解析继承的resultMap
    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<>(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) {
        extendedResultMappings.removeIf(resultMapping -> resultMapping.getFlags().contains(ResultFlag.CONSTRUCTOR));
      }
      // 继承的resultMap也添加到resultMappings中
      resultMappings.addAll(extendedResultMappings);
    }
    // 构建一个resultMap对象
    ResultMap resultMap = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping)
        .discriminator(discriminator).build();
    // 把resultMap添加到configuration对象的resultMaps中
    configuration.addResultMap(resultMap);
    return resultMap;
  }

sql

sql节点可以用来定义可重用的 SQL 代码片段,以便在其它语句中使用。 参数可以静态地(在加载的时候)确定下来,并且可以在不同的 include 元素中定义不同的参数值.
解析是在sqlElement(List list, String requiredDatabaseId)方法中,最终会把sql节点对象放到configuration#sqlFragments对象中的

private void  sqlElement(List<XNode> list, String requiredDatabaseId) {
    for (XNode context : list) {
      String databaseId = context.getStringAttribute("databaseId");
      String id = context.getStringAttribute("id");
      id = builderAssistant.applyCurrentNamespace(id, false);
      if (databaseIdMatchesCurrent(id, databaseId, requiredDatabaseId)) {
        sqlFragments.put(id, context);
      }
    }
  }

select|insert|update|delete

select|insert|update|delete节点解析是在buildStatementFromContext(List list, String requiredDatabaseId),在buildStatementFromContext中会引出配置解析节点的第三个重要的类XMLStatementBuilder,在XMLStatementBuilder#parseStatementNode方法中。

private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
    for (XNode context : list) {
      final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
      try {
        statementParser.parseStatementNode();
      } catch (IncompleteElementException e) {
        configuration.addIncompleteStatement(statementParser);
      }
    }
  }

能力有限,水平一般,如有错误,请多指出。

posted @ 2022-04-29 19:05  码猿笔记  阅读(106)  评论(0编辑  收藏  举报