深入Mybatis原始碼——配置解析

夜勿語發表於2020-07-07

@

前言

上一篇分析了Mybatis的基礎元件,Mybatis的執行呼叫就是建立在這些基礎元件之上的,那它的執行原理又是怎樣的呢?在往下之前不妨先思考下如果是你會怎麼實現。

正文

熟悉Mybatis的都知道,在使用Mybatis時需要配置一個mybatis-config.xml檔案,另外還需要定義Mapper介面和Mapper.xml檔案,在config檔案中引入或掃描對應的包才能被載入解析(現在由於大多是SpringBoot工程,基本上都不會配置config檔案,而是通過註解進行掃描就行了,但本質上的實現和xml配置沒有太大區別,所以本篇仍以xml配置方式進行分析。),所以Mybatis的第一個階段必然是要去載入並解析配置檔案,這個階段在專案啟動時就應該完成,後面直接呼叫即可。載入完成之後,自然就是等待呼叫,但是我們在專案中只會定義Mapper介面和Mapper.xml檔案,那具體的實現類在哪呢?Mybatis是通過動態代理實現的,所以第二個階段應該是生成Mapper介面的代理實現類。通過呼叫代理類,最終會生成對應的sql訪問資料庫並獲取結果,所以最後一個階段就是SQL解析(引數對映、SQL對映、結果對映)。本文主要分析配置解析階段。

配置解析

Mybatis可以通過下面的方式解析配置檔案:

    final String resource = "org/apache/ibatis/builder/MapperConfig.xml";
    final Reader reader = Resources.getResourceAsReader(resource);
    SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);

所以入口就是build方法(從名字可以看出使用了建造者模式,它和工廠模式一樣,也是解用於建立物件的一種模式,不過與工廠模式不一樣的是,前者需要我們自己參與構建的細節,而後者則不需要):

  public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      //讀取配置檔案
      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
      return build(parser.parse());//解析配置檔案得到configuration物件,並返回SqlSessionFactory
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error building SqlSession.", e);
    } finally {
      ErrorContext.instance().reset();
      try {
        reader.close();
      } catch (IOException e) {
        // Intentionally ignore. Prefer previous error.
      }
    }
  }

這裡先是建立了一個XMLConfigBuilder物件,這個物件就是用來載入解析config檔案的,先看看它的構造方法中做了些什麼事情:

  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
    this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    super(new Configuration());
    ErrorContext.instance().resource("SQL Mapper Configuration");
    this.configuration.setVariables(props);
    this.parsed = false;
    this.environment = environment;
    this.parser = parser;
  }

需要注意的是這裡建立了一個Configuration物件,他就是Mybatis的核心CPU,儲存了所有的配置資訊,在後面的執行階段所需要的資訊都是從這個類取的,因為這個類比較大,這裡就不貼詳細程式碼了,讀者請務必閱讀原始碼熟悉該類。因為這個類物件儲存了所有的配置資訊,那麼必然這個類是全域性單例的,事實上這個物件的建立也只有這裡一個入口,保證了全域性唯一。
在該類的構造方法中,首先就註冊了核心元件的別名和對應的類對映關係:

  public Configuration() {
    typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
    typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);

    typeAliasRegistry.registerAlias("JNDI", JndiDataSourceFactory.class);
    typeAliasRegistry.registerAlias("POOLED", PooledDataSourceFactory.class);
    typeAliasRegistry.registerAlias("UNPOOLED", UnpooledDataSourceFactory.class);

	......省略

    languageRegistry.setDefaultDriverClass(XMLLanguageDriver.class);
    languageRegistry.register(RawLanguageDriver.class);
  }

而註冊類在例項化時同樣也註冊了一些基礎型別的別名對映:

  public TypeAliasRegistry() {
    registerAlias("string", String.class);

    registerAlias("byte", Byte.class);
    registerAlias("long", Long.class);
    registerAlias("short", Short.class);
    registerAlias("int", Integer.class);
    registerAlias("integer", Integer.class);
    registerAlias("double", Double.class);
    registerAlias("float", Float.class);
    registerAlias("boolean", Boolean.class);

	......省略
	
    registerAlias("ResultSet", ResultSet.class);
  }

看到這相信你就知道parameterType和resultType屬性的簡寫是怎麼實現的了。回到主流程,進入到parser.parse方法中:

  public Configuration parse() {
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

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

這個方法就是去解析配置檔案中的各個節點,並將其封裝到Configuration物件中去,前面的節點解析沒啥好說的,自己看一下就明白了,重點看一下最後一個對mapper節點的解析,這個就是載入我們的Mapper.xml檔案:

  <mappers>
    <mapper resource="org/apache/ibatis/builder/AuthorMapper.xml"/>
    <mapper resource="org/apache/ibatis/builder/BlogMapper.xml"/>
    <mapper resource="org/apache/ibatis/builder/CachedAuthorMapper.xml"/>
    <mapper resource="org/apache/ibatis/builder/PostMapper.xml"/>
    <mapper resource="org/apache/ibatis/builder/NestedBlogMapper.xml"/>
  </mappers>
 private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {//處理mapper子節點
        if ("package".equals(child.getName())) {//package子節點
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {//獲取<mapper>節點的resource、url或mClass屬性這三個屬性互斥
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {//如果resource不為空
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);//載入mapper檔案
            //例項化XMLMapperBuilder解析mapper對映檔案
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url != null && mapperClass == null) {//如果url不為空
            ErrorContext.instance().resource(url);
            InputStream inputStream = Resources.getUrlAsStream(url);//載入mapper檔案
            //例項化XMLMapperBuilder解析mapper對映檔案
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
          } else if (resource == null && url == null && mapperClass != null) {//如果class不為空
            Class<?> mapperInterface = Resources.classForName(mapperClass);//載入class物件
            configuration.addMapper(mapperInterface);//向代理中心註冊mapper
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

從上面的程式碼中我們可以看到這裡有兩種配置方式,一種是配置package子節點,即掃描並批量載入指定的包中的檔案;另一種則是使用mapper子節點引入單個檔案,而mapper節點又可以配置三種屬性:resource、url、class。而解析XML的核心類是XMLMapperBuilder,進入parse方法:

  public void parse() {
	//判斷是否已經載入該配置檔案
    if (!configuration.isResourceLoaded(resource)) {
      configurationElement(parser.evalNode("/mapper"));//處理mapper節點
      configuration.addLoadedResource(resource);//將mapper檔案新增到configuration.loadedResources中
      bindMapperForNamespace();//註冊mapper介面
    }
    //處理解析失敗的ResultMap節點
    parsePendingResultMaps();
    //處理解析失敗的CacheRef節點
    parsePendingCacheRefs();
    //處理解析失敗的Sql語句節點
    parsePendingStatements();
  }

  private void configurationElement(XNode context) {
    try {
    	//獲取mapper節點的namespace屬性
      String namespace = context.getStringAttribute("namespace");
      if (namespace == null || namespace.equals("")) {
        throw new BuilderException("Mapper's namespace cannot be empty");
      }
      //設定builderAssistant的namespace屬性
      builderAssistant.setCurrentNamespace(namespace);
      //解析cache-ref節點
      cacheRefElement(context.evalNode("cache-ref"));
      //重點分析 :解析cache節點----------------1-------------------
      cacheElement(context.evalNode("cache"));
      //解析parameterMap節點(已廢棄)
      parameterMapElement(context.evalNodes("/mapper/parameterMap"));
      //重點分析 :解析resultMap節點(基於資料結果去理解)----------------2-------------------
      resultMapElements(context.evalNodes("/mapper/resultMap"));
      //解析sql節點
      sqlElement(context.evalNodes("/mapper/sql"));
      //重點分析 :解析select、insert、update、delete節點 ----------------3-------------------
      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);
    }
  }

核心的處理邏輯又是通過configurationElement實現的,接下來挨個分析幾個重要節點解析過程。

1. cacheRefElement/cacheElement

這兩個節點都是解析二級快取配置的,前者是引用其它namespace的二級快取,後者則是直接開啟當前namespace的二級快取,所以重點看後者:

  private void cacheElement(XNode context) throws Exception {
    if (context != null) {
      //獲取cache節點的type屬性,預設為PERPETUAL
      String type = context.getStringAttribute("type", "PERPETUAL");
      //找到type對應的cache介面的實現
      Class<? extends Cache> typeClass = typeAliasRegistry.resolveAlias(type);
      //讀取eviction屬性,既快取的淘汰策略,預設LRU
      String eviction = context.getStringAttribute("eviction", "LRU");
      //根據eviction屬性,找到裝飾器
      Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction);
      //讀取flushInterval屬性,既快取的重新整理週期
      Long flushInterval = context.getLongAttribute("flushInterval");
      //讀取size屬性,既快取的容量大小
      Integer size = context.getIntAttribute("size");
     //讀取readOnly屬性,既快取的是否只讀
      boolean readWrite = !context.getBooleanAttribute("readOnly", false);
      //讀取blocking屬性,既快取的是否阻塞
      boolean blocking = context.getBooleanAttribute("blocking", false);
      Properties props = context.getChildrenAsProperties();
      //通過builderAssistant建立快取物件,並新增至configuration
      builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props);
    }
  }

  public Cache useNewCache(Class<? extends Cache> typeClass,
      Class<? extends Cache> evictionClass,
      Long flushInterval,
      Integer size,
      boolean readWrite,
      boolean blocking,
      Properties props) {
	//經典的建造起模式,建立一個cache物件
    Cache cache = new CacheBuilder(currentNamespace)
        .implementation(valueOrDefault(typeClass, PerpetualCache.class))
        .addDecorator(valueOrDefault(evictionClass, LruCache.class))
        .clearInterval(flushInterval)
        .size(size)
        .readWrite(readWrite)
        .blocking(blocking)
        .properties(props)
        .build();
    //將快取新增至configuration,注意二級快取以名稱空間為單位進行劃分
    configuration.addCache(cache);
    currentCache = cache;
    return cache;
  }

  public void addCache(Cache cache) {
    caches.put(cache.getId(), cache);
  }

從這裡我們可以看到預設建立了PerpetualCache物件,這個是快取的基本實現類,然後根據配置給快取加上裝飾器,預設會裝飾LRU。配置解析完成後,才會通過MapperBuilderAssistant類真正建立快取物件並新增到Configuration物件中。為什麼這裡要通過MapperBuilderAssistant物件建立快取物件呢?從名字可以看出它是XMLMapperBuilder的協助者,因為XML的解析和配置物件的裝填是非常繁瑣的一個過程,如果全部由一個類來完成,會非常的臃腫難看,並且耦合性較高,所以這裡又僱傭了一個“協助者”。

2. resultMapElements

  private void resultMapElements(List<XNode> list) throws Exception {
	//遍歷所有的resultmap節點
    for (XNode resultMapNode : list) {
      try {
    	 //解析具體某一個resultMap節點
        resultMapElement(resultMapNode);
      } catch (IncompleteElementException e) {
        // ignore, it will be retried
      }
    }
  }

  private ResultMap resultMapElement(XNode resultMapNode, List<ResultMapping> additionalResultMappings) throws Exception {
    ErrorContext.instance().activity("processing " + resultMapNode.getValueBasedIdentifier());
    //獲取resultmap節點的id屬性
    String id = resultMapNode.getStringAttribute("id",
        resultMapNode.getValueBasedIdentifier());
    //獲取resultmap節點的type屬性
    String type = resultMapNode.getStringAttribute("type",
        resultMapNode.getStringAttribute("ofType",
            resultMapNode.getStringAttribute("resultType",
                resultMapNode.getStringAttribute("javaType"))));
    //獲取resultmap節點的extends屬性,描述繼承關係
    String extend = resultMapNode.getStringAttribute("extends");
    //獲取resultmap節點的autoMapping屬性,是否開啟自動對映
    Boolean autoMapping = resultMapNode.getBooleanAttribute("autoMapping");
    //從別名註冊中心獲取entity的class物件
    Class<?> typeClass = resolveClass(type);
    Discriminator discriminator = null;
    //記錄子節點中的對映結果集合
    List<ResultMapping> resultMappings = new ArrayList<>();
    resultMappings.addAll(additionalResultMappings);
    //從xml檔案中獲取當前resultmap中的所有子節點,並開始遍歷
    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 {//處理<id> <result> <association> <collection>節點
        List<ResultFlag> flags = new ArrayList<>();
        if ("id".equals(resultChild.getName())) {
          flags.add(ResultFlag.ID);//如果是id節點,向flags中新增元素
        }
        //建立ResultMapping物件並加入resultMappings集合中
        resultMappings.add(buildResultMappingFromContext(resultChild, typeClass, flags));
      }
    }
    //例項化resultMap解析器
    ResultMapResolver resultMapResolver = new ResultMapResolver(builderAssistant, id, typeClass, extend, discriminator, resultMappings, autoMapping);
    try {
      //通過resultMap解析器例項化resultMap並將其註冊到configuration物件
      return resultMapResolver.resolve();
    } catch (IncompleteElementException  e) {
      configuration.addIncompleteResultMap(resultMapResolver);
      throw e;
    }
  }

這個方法同樣先是解析節點的屬性,然後通過buildResultMappingFromContext方法建立ResultMapping物件並封裝到ResultMapResolver中去,最後還是通過MapperBuilderAssistant例項化ResultMap物件並新增到ConfigurationresultMaps屬性中:

  public ResultMap addResultMap(
      String id,
      Class<?> type,
      String extend,
      Discriminator discriminator,
      List<ResultMapping> resultMappings,
      Boolean autoMapping) {
	 //完善id,id的完整格式是"namespace.id"
    id = applyCurrentNamespace(id, false);
    //獲得父類resultMap的完整id
    extend = applyCurrentNamespace(extend, true);

    //針對extend屬性的處理
    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) {
        Iterator<ResultMapping> extendedResultMappingsIter = extendedResultMappings.iterator();
        while (extendedResultMappingsIter.hasNext()) {
          if (extendedResultMappingsIter.next().getFlags().contains(ResultFlag.CONSTRUCTOR)) {
            extendedResultMappingsIter.remove();
          }
        }
      }
      //新增需要被繼承下來的resultMapping物件結合
      resultMappings.addAll(extendedResultMappings);
    }
    //通過建造者模式例項化resultMap,並註冊到configuration.resultMaps中
    ResultMap resultMap = new ResultMap.Builder(configuration, id, type, resultMappings, autoMapping)
        .discriminator(discriminator)
        .build();
    configuration.addResultMap(resultMap);
    return resultMap;
  }

3. sqlElement

解析SQL節點,只是將其快取到XMLMapperBuildersqlFragments屬性中。

4. buildStatementFromContext

  private void buildStatementFromContext(List<XNode> list) {
    if (configuration.getDatabaseId() != null) {
      buildStatementFromContext(list, configuration.getDatabaseId());
    }
    buildStatementFromContext(list, null);
  }

  private void buildStatementFromContext(List<XNode> list, String requiredDatabaseId) {
    for (XNode context : list) {
      //建立XMLStatementBuilder 專門用於解析sql語句節點
      final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
      try {
    	//解析sql語句節點
        statementParser.parseStatementNode();
      } catch (IncompleteElementException e) {
        configuration.addIncompleteStatement(statementParser);
      }
    }
  }

這個方法是重點,通過XMLStatementBuilder物件解析select、update、insert、delete節點:

  public void parseStatementNode() {
	//獲取sql節點的id
    String id = context.getStringAttribute("id");
    String databaseId = context.getStringAttribute("databaseId");

    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
      return;
    }
    /*獲取sql節點的各種屬性*/
    Integer fetchSize = context.getIntAttribute("fetchSize");
    Integer timeout = context.getIntAttribute("timeout");
    String parameterMap = context.getStringAttribute("parameterMap");
    String parameterType = context.getStringAttribute("parameterType");
    Class<?> parameterTypeClass = resolveClass(parameterType);
    String resultMap = context.getStringAttribute("resultMap");
    String resultType = context.getStringAttribute("resultType");
    String lang = context.getStringAttribute("lang");
    LanguageDriver langDriver = getLanguageDriver(lang);

    Class<?> resultTypeClass = resolveClass(resultType);
    String resultSetType = context.getStringAttribute("resultSetType");
    StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
    ResultSetType resultSetTypeEnum = resolveResultSetType(resultSetType);

    
    
    //根據sql節點的名稱獲取SqlCommandType(INSERT, UPDATE, DELETE, SELECT)
    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
    //在解析sql語句之前先解析<include>節點
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());

    // Parse selectKey after includes and remove them.
    //在解析sql語句之前,處理<selectKey>子節點,並在xml節點中刪除
    processSelectKeyNodes(id, parameterTypeClass, langDriver);
    
    // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
    //解析sql語句是解析mapper.xml的核心,例項化sqlSource,使用sqlSource封裝sql語句
    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    String resultSets = context.getStringAttribute("resultSets");//獲取resultSets屬性
    String keyProperty = context.getStringAttribute("keyProperty");//獲取主鍵資訊keyProperty
    String keyColumn = context.getStringAttribute("keyColumn");///獲取主鍵資訊keyColumn
    
    //根據<selectKey>獲取對應的SelectKeyGenerator的id
    KeyGenerator keyGenerator;
    String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
    keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
    
    
    //獲取keyGenerator物件,如果是insert型別的sql語句,會使用KeyGenerator介面獲取資料庫生產的id;
    if (configuration.hasKeyGenerator(keyStatementId)) {
      keyGenerator = configuration.getKeyGenerator(keyStatementId);
    } else {
      keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
          configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
          ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
    }

    //通過builderAssistant例項化MappedStatement,並註冊至configuration物件
    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
        resultSetTypeEnum, flushCache, useCache, resultOrdered, 
        keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
  }

  public MappedStatement addMappedStatement(
      String id,
      SqlSource sqlSource,
      StatementType statementType,
      SqlCommandType sqlCommandType,
      Integer fetchSize,
      Integer timeout,
      String parameterMap,
      Class<?> parameterType,
      String resultMap,
      Class<?> resultType,
      ResultSetType resultSetType,
      boolean flushCache,
      boolean useCache,
      boolean resultOrdered,
      KeyGenerator keyGenerator,
      String keyProperty,
      String keyColumn,
      String databaseId,
      LanguageDriver lang,
      String resultSets) {

    if (unresolvedCacheRef) {
      throw new IncompleteElementException("Cache-ref not yet resolved");
    }

    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;
  }

同樣的,最後根據sql語句和屬性例項化MappedStatement物件,並新增到Configuration物件的mappedStatements屬性中。

回到XMLMapperBuilder.parse方法中,在解析完xml之後又呼叫了bindMapperForNamespace方法:

  private void bindMapperForNamespace() {
	//獲取名稱空間
    String namespace = builderAssistant.getCurrentNamespace();
    if (namespace != null) {
      Class<?> boundType = null;
      try {
    	//通過名稱空間獲取mapper介面的class物件
        boundType = Resources.classForName(namespace);
      } catch (ClassNotFoundException e) {
        //ignore, bound type is not required
      }
      if (boundType != null) {
        if (!configuration.hasMapper(boundType)) {//是否已經註冊過該mapper介面?
          // Spring may not know the real resource name so we set a flag
          // to prevent loading again this resource from the mapper interface
          // look at MapperAnnotationBuilder#loadXmlResource
          //將名稱空間新增至configuration.loadedResource集合中
          configuration.addLoadedResource("namespace:" + namespace);
          //將mapper介面新增到mapper註冊中心
          configuration.addMapper(boundType);
        }
      }
    }
  }

這個方法中首先通過namespace拿到xml對應的Mapper介面型別,然後委託給Configuration類中的mapperRegistry註冊動態的代理的工廠MapperProxyFactory

  public <T> void addMapper(Class<T> type) {
    if (type.isInterface()) {
        if (hasMapper(type)) {
          throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
        }
      boolean loadCompleted = false;
      try {
    	//例項化Mapper介面的代理工程類,並將資訊新增至knownMappers
        knownMappers.put(type, new MapperProxyFactory<T>(type));
        // It's important that the type is added before the parser is run
        // otherwise the binding may automatically be attempted by the
        // mapper parser. If the type is already known, it won't try.
        //解析介面上的註解資訊,並新增至configuration物件
        MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
        parser.parse();
        loadCompleted = true;
      } finally {
        if (!loadCompleted) {
          knownMappers.remove(type);
        }
      }
    }
  }

這個就是建立Mapper介面的動態代理物件的工廠類,所以Mapper的代理物件實際上並不是在啟動的時候就建立好了,而是在方法呼叫時才會建立,為什麼會這麼設計呢?因為代理物件和SqlSession是一一對應的,而我們每一次呼叫Mapper的方法都是建立一個新的SqlSession,所以這裡只是快取了代理工廠物件。
代理工廠註冊之後還通過MapperAnnotationBuilder類提供了對註解方式的支援,這裡就不闡述了,結果就是將註解的值新增到Configuration中去。

總結

解析配置檔案的流程雖然比較長,但邏輯一點都不復雜,主要就是獲取xml配置的屬性值,例項化不同的配置物件,並將這些配置都丟到Configuration物件中去,我們只需要重點關注哪些物件被註冊到了Configuration中去,最後根據Configuration物件例項化DefaultSqlSessionFactory物件並返回,而DefaultSqlSessionFactory就是用來建立SqlSession物件的,這個物件就是上一篇架構圖中的介面層,它提供了所有訪問資料庫的操作並遮蔽了底層複雜實現細節,具體的實現原理將在下一篇進行分析。

相關文章