小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件

mybatis源码分析系列:

  1. mybatis源码看这一遍就够了(1)| 前言
  2. mybatis源码看这一遍就够了(2)| getMapper
  3. mybatis源码看这一遍就够了(3)| Configuration及解析配置文件
  4. mybatis源码看这一遍就够了(4)| SqlSession.select调用分析
  5. mybatis源码看这一遍就够了(5)| 与springboot整合

这一章我们来针对上一章遗留的问题进行分析,包括mappedStatements、knownMappers从何而来,Configuration做了些什么?


我们直接从我们第一章的例子入手: 

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("configuration.xml"));

这么短短的一句一句话究竟做了哪些不为人知的事,我们点进SqlSessionFactoryBuilder.build()方法:

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第1张图片

首先构造初始化了XMLConfigBuilder,然后调用parser.parse()开始解析和返回configuration对象:

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第2张图片

可以看到parseConfiguration解析我们的配置文configuration.xml的节点下的数据:

private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

看到这些节点名是不是很熟悉,它就是configuration配置文件的节点,比如我们配置的environments和mappers:

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第3张图片

那我们下面就只看我们demo里这两个用到的节点,其他都是大同小异,我们先看下environments节点的解析:

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第4张图片

这里圈红位置就是获取dataSource节点下的配置数据,然后将其解析成Properties然后放入DataSource里面

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第5张图片

然后将构建好的 DataSource放入Environment对象中,紧接着就是将Environment放在configuration对象里。

 

好了下面说下mapper节点的解析mapperElement(root.evalNode("mappers")):

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            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);
            InputStream inputStream = Resources.getUrlAsStream(url);
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url == null && mapperClass != null) {
            Class mapperInterface = Resources.classForName(mapperClass);
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }
String resource = child.getStringAttribute("resource");

这句不正是解析configuration.xml里配置的

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第6张图片

这里拿到Mapper的sql配置文件名mybatis/UserMapper.xml;紧接着就是解析UserMapper.xml文件

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第7张图片

解析UserMapper.xml文件mapper节点

 小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第8张图片

调用configurationElement:

  private void configurationElement(XNode context) {
    try {
      String namespace = context.getStringAttribute("namespace");
      if (namespace == null || namespace.equals("")) {
        throw new BuilderException("Mapper's namespace cannot be empty");
      }
      builderAssistant.setCurrentNamespace(namespace);
      cacheRefElement(context.evalNode("cache-ref"));
      cacheElement(context.evalNode("cache"));
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
      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);
    }
  }

这里面就是对UserMapper.xml文件的解析,可以看到些熟悉的字眼,比如我们配的namespace,还有就是select:

我们进入buildStatementFromContext(context.evalNodes("select|insert|update|delete")):

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第9张图片

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第10张图片

遍历拿到的所有select|insert|update|delete节点,然后调用statementParser.parseStatementNode()进行解析:

public void parseStatementNode() {
    String id = context.getStringAttribute("id");
    String databaseId = context.getStringAttribute("databaseId");

    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
      return;
    }

    String nodeName = context.getNode().getNodeName();
    SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
    boolean useCache = context.getBooleanAttribute("useCache", isSelect);
    boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

    // Include Fragments before parsing
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());

    String parameterType = context.getStringAttribute("parameterType");
    Class parameterTypeClass = resolveClass(parameterType);

    String lang = context.getStringAttribute("lang");
    LanguageDriver langDriver = getLanguageDriver(lang);

    // Parse selectKey after includes and remove them.
    processSelectKeyNodes(id, parameterTypeClass, langDriver);

    // Parse the SQL (pre:  and  were parsed and removed)
    KeyGenerator keyGenerator;
    String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
    if (configuration.hasKeyGenerator(keyStatementId)) {
      keyGenerator = configuration.getKeyGenerator(keyStatementId);
    } else {
      keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
          configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
          ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
    }

    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
    Integer fetchSize = context.getIntAttribute("fetchSize");
    Integer timeout = context.getIntAttribute("timeout");
    String parameterMap = context.getStringAttribute("parameterMap");
    String resultType = context.getStringAttribute("resultType");
    Class resultTypeClass = resolveClass(resultType);
    String resultMap = context.getStringAttribute("resultMap");
    String resultSetType = context.getStringAttribute("resultSetType");
    ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);
    if (resultSetTypeEnum == null) {
      resultSetTypeEnum = configuration.getDefaultResultSetType();
    }
    String keyProperty = context.getStringAttribute("keyProperty");
    String keyColumn = context.getStringAttribute("keyColumn");
    String resultSets = context.getStringAttribute("resultSets");

    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
        resultSetTypeEnum, flushCache, useCache, resultOrdered,
        keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
  }

这里面就是对整个mapper文件进行了解析操作,包括拿到id;sql语句呀等等,然后将其组装成MappedStatement:

builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
        resultSetTypeEnum, flushCache, useCache, resultOrdered,
        keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);

进入builderAssistant.addMappedStatement方法下面部分代码:

id = applyCurrentNamespace(id, false);
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
        .resource(resource)
        .fetchSize(fetchSize)
        .timeout(timeout)
        .statementType(statementType)
        .keyGenerator(keyGenerator)
        .keyProperty(keyProperty)
        .keyColumn(keyColumn)
        .databaseId(databaseId)
        .lang(lang)
        .resultOrdered(resultOrdered)
        .resultSets(resultSets)
        .resultMaps(getStatementResultMaps(resultMap, resultType, id))
        .resultSetType(resultSetType)
        .flushCacheRequired(valueOrDefault(flushCache, !isSelect))
        .useCache(valueOrDefault(useCache, isSelect))
        .cache(currentCache);

    ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
    if (statementParameterMap != null) {
      statementBuilder.parameterMap(statementParameterMap);
    }

    MappedStatement statement = statementBuilder.build();
    configuration.addMappedStatement(statement);
    return statement;

获取id,有namespace+.id组成id值

  public String applyCurrentNamespace(String base, boolean isReference) {
    ...省略
    return currentNamespace + "." + base;
  }

 new MappedStatement.Builder创建了一个MappedStatement,然后对解析出来的节点数据进行赋值放在MappedStatement:

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第11张图片

最后将其 MappedStatement放入configuration对象中

其实这里就是调用addMappedStatement方法将其key为namespace+.id,value为MappedStatement放入Map mappedStatements,到这里是不是就回答了上一章mybatis源码看这一遍就够了(2)中间提到的mappedStatements哪里来的问题。也回答了configuration这个对象究竟做了些啥这个问题。

然后我们继续回到上面XMLMapperBuilder.parse这里:

 public void parse() {
    if (!configuration.isResourceLoaded(resource)) {
      configurationElement(parser.evalNode("/mapper"));
      configuration.addLoadedResource(resource);
      bindMapperForNamespace();
    }

    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
  }

解析完mapper文件接着调用bindMapperForNamespace():

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第12张图片

判断configuration.hasMapper(boundType)是否已经解析过有存在:

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第13张图片

当然我们这里还是没有放入knownMappers这个map里面的,那么久进入configuration.addMapper(boundType):

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第14张图片

小白mybatis源码看这一遍就够了(3)| Configuration及解析配置文件_第15张图片

到这里是不是可以看到创建MapperProxyFactory<>(type),key为type然后放入knownMappers这个map里面,这个不就回答了我们上一章的问题knownMappersmybatis源码看这一遍就够了(2)从何而来吗。

好了,其他的解析我就不再赘述了,因为太多内容,其实都是大同小异的东西,大家可以自己跟一下源码很快就能get到的。

上一章还有遗留一个问题未解答,sqlSession.selectList这一步究竟做了啥,这和jdbc又有什么关系,我们下一章mybatis源码看一遍就够了(4)继续分析

 

你可能感兴趣的:(mybaits)