主頁 > 後端開發 > 深入Mybatis原始碼——配置決議

深入Mybatis原始碼——配置決議

2020-10-03 00:29:26 後端開發

@

目錄
  • 前言
  • 正文
    • 配置決議
      • 1. cacheRefElement/cacheElement
      • 2. resultMapElements
      • 3. sqlElement
      • 4. buildStatementFromContext
  • 總結

前言

上一篇分析了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物件的,這個物件就是上一篇架構圖中的介面層,它提供了所有訪問資料庫的操作并屏蔽了底層復雜實作細節,具體的實作原理將在下一篇進行分析,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/149780.html

標籤:Java

上一篇:送給你 12 個 Git 使用技巧!

下一篇:微服務架構的前世今生(七):微服務架構生態體系

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more