亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Mybatis核心配置文件加載流程詳解

 更新時(shí)間:2023年12月13日 09:07:32   作者:JermeryBesian  
本文將介紹MyBatis在配置文件加載的過(guò)程中,如何加載核心配置文件、如何解析映射文件中的SQL語(yǔ)句以及每條SQL語(yǔ)句如何與映射接口的方法進(jìn)行關(guān)聯(lián),具有一定的參考價(jià)值,感興趣的可以了解一下

本文將介紹MyBatis在配置文件加載的過(guò)程中,如何加載核心配置文件、如何解析映射文件中的SQL語(yǔ)句以及每條SQL語(yǔ)句如何與映射接口的方法進(jìn)行關(guān)聯(lián)。

映射配置文件

在介紹核心配置文件加載流程前,先給出一個(gè)簡(jiǎn)單的MyBatis的配置文件mybatis-config.xml如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="cacheEnabled" value="true"/>
        <setting name="localCacheScope" value="STATEMENT"/>

    </settings>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/local?allowPublicKeyRetrieval=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="mapper/UserMapper.xml"/>
        <mapper resource="mapper/OrderMapper.xml"/>
    </mappers>
</configuration>

上面的XMl配置文件中,包含了一些核心標(biāo)簽,比如

  • <settings> 標(biāo)簽:用于配置 MyBatis 的全局設(shè)置,包括設(shè)置緩存、懶加載、日志實(shí)現(xiàn)、數(shù)據(jù)庫(kù)元信息獲取方式等。您可以在這里定義各種全局設(shè)置,以定制 MyBatis 的行為。
  • <environments> 標(biāo)簽:用于配置 MyBatis 的數(shù)據(jù)庫(kù)環(huán)境,包括數(shù)據(jù)源信息、事務(wù)管理器等。這個(gè)標(biāo)簽允許您配置多個(gè)環(huán)境,每個(gè)環(huán)境可以包含一個(gè)或多個(gè)數(shù)據(jù)源,以及相應(yīng)的事務(wù)管理器。
  • <mappers> 標(biāo)簽:用于指定 MyBatis 映射器(Mapper)接口或映射文件的位置。在這個(gè)標(biāo)簽中,您可以列出要使用的 Mapper 接口或 XML 映射文件,MyBatis 將會(huì)加載這些映射器并將其配置為可用的映射器。

<mappers>標(biāo)簽中,有下面兩種子節(jié)點(diǎn),標(biāo)簽分別為<mapper><package>,這兩種標(biāo)簽的說(shuō)明如下所示:

  • <mapper>:該標(biāo)簽有三種屬性,分別是resource、url和class,且在同一個(gè)標(biāo)簽中,只能設(shè)置其中一個(gè)。其中,resource和url屬性均是通過(guò)告訴MyBatis映射文件所在的位置路徑來(lái)注冊(cè)映射文件,前者使用相對(duì)路徑(相對(duì)于classpath,例如上面的mapper/UserMapper.xml),后者使用絕對(duì)路徑。 class屬性是通過(guò)告訴MyBatis映射文件對(duì)應(yīng)的映射接口的全限定名來(lái)注冊(cè)映射接口,此時(shí)要求映射文件與映射接口同名且同目錄。
  • <package>:通過(guò)設(shè)置映射接口所在包名來(lái)注冊(cè)映射接口,此時(shí)要求映射文件與映射接口同名且同目錄。

上面列出了一些概念性的點(diǎn),接下來(lái)我們通過(guò)源碼來(lái)分析MyBatis是如何來(lái)加載和解析上面的配置文件的,并在源碼中找到上面概念的佐證。

加載映射文件的源碼分析

在讀取配置文件時(shí),我們通常會(huì)使用Resources.getResourceAsStream方法,利用字節(jié)輸入流來(lái)讀取配置文件。接下來(lái),利用SqlSessionFactoryBuilderbuild方法,來(lái)讀取該輸入流,并將文件內(nèi)容進(jìn)行解析,加載到MyBatis中全局唯一的Configuration配置類中,從而完成配置文件的加載。代碼如下所示:

InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

SqlSession sqlSession = sqlSessionFactory.openSession();

SqlSessionFactoryBuilder是一個(gè)建造者,其提供了共計(jì)9個(gè)重載的build()方法用于構(gòu)建SqlSessionFactory,這9個(gè)build()方法可以分為三類,概括如下:

  • 基于配置文件字符流構(gòu)建SqlSessionFactory
  • 基于配置文件字節(jié)流構(gòu)建SqlSessionFactory;
  • 基于Configuration類構(gòu)建SqlSessionFactory。

下面以基于配置文件字節(jié)流構(gòu)建SqlSessionFactory的過(guò)程為例,對(duì)整個(gè)讀配置文件的流程進(jìn)行說(shuō)明。上面的示例中調(diào)用的build() 方法最終會(huì)進(jìn)入到下面的方法中:

public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  try {
    // XMLConfigBuiler會(huì)解析配置文件并生成Configuration類
    XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
    // 調(diào)用入?yún)镃onfiguration的build()方法構(gòu)建SqlSessionFactory并返回
    return build(parser.parse());
  } catch (Exception e) {
    throw ExceptionFactory.wrapException("Error building SqlSession.", e);
  } finally {
    ErrorContext.instance().reset();
    try {
      inputStream.close();
    } catch (IOException e) {
      // Intentionally ignore. Prefer previous error.
    }
  }
}

可以發(fā)現(xiàn),對(duì)配置文件的解析是在XMLConfigBuilderparse()方法中的。先來(lái)看一下上面創(chuàng)建的XMLConfigBuilder實(shí)例:

public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
  this(new XPathParser(inputStream, 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;
}

可以看到XMLConfigBuilder對(duì)XML的解析是依靠XPathParser,而XPathParser是MyBatis提供的基于JAVA XPath的解析器。同時(shí),XMLConfigBuilder通過(guò)繼承BaseBuilder,在內(nèi)部維護(hù)了一個(gè)Configuration,通過(guò)XPathParser解析得到的配置屬性均會(huì)保存在Configuration中。
另外,在上面的new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()方法中,MyBatis會(huì)借助于DOMParser 來(lái)將配置文件的輸入流解析成Document來(lái)表示。

public Document parse(InputSource is) throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException(
            DOMMessageFormatter.formatMessage(DOMMessageFormatter.DOM_DOMAIN,
            "jaxp-null-input-source", null));
    }
    if (fSchemaValidator != null) {
        if (fSchemaValidationManager != null) {
            fSchemaValidationManager.reset();
            fUnparsedEntityHandler.reset();
        }
        resetSchemaValidator();
    }
    // 利用DOMParser將配置文件字節(jié)輸入流解析成Document對(duì)象 
    domParser.parse(is);
    Document doc = domParser.getDocument();
    domParser.dropDocumentReferences();
    return doc;
}

回到上面的parse()方法中:

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

其中,parser.evalNode("/configuration")就是從上面解析好的 Document對(duì)象中,利用xPath獲取到configuration標(biāo)簽(根節(jié)點(diǎn)),然后將<configuration標(biāo)簽下的內(nèi)容傳入parseConfiguration方法中。該方法中其實(shí)也就是相同的利用xPath來(lái)獲取指定標(biāo)簽下的內(nèi)容:

private void parseConfiguration(XNode root) {
  try {
    //issue #117 read properties first
    // 獲取properties標(biāo)簽下的內(nèi)容進(jìn)行處理
    propertiesElement(root.evalNode("properties"));
	// 獲取settings標(biāo)簽下的內(nèi)容
    Properties settings = settingsAsProperties(root.evalNode("settings"));
    loadCustomVfs(settings);
    loadCustomLogImpl(settings);
    // 獲取typeAliases標(biāo)簽下的內(nèi)容
    typeAliasesElement(root.evalNode("typeAliases"));
    // 獲取plugins標(biāo)簽下的內(nèi)容
    pluginElement(root.evalNode("plugins"));
    // 獲取objectFactory標(biāo)簽下的內(nèi)容
    objectFactoryElement(root.evalNode("objectFactory"));
    // 獲取objectWrapperFactory標(biāo)簽下的內(nèi)容
    objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
    // 獲取reflectorFactory標(biāo)簽下的內(nèi)容
    reflectorFactoryElement(root.evalNode("reflectorFactory"));
    settingsElement(settings);
    // read it after objectFactory and objectWrapperFactory issue #631
    // 獲取environments標(biāo)簽下的內(nèi)容
    environmentsElement(root.evalNode("environments"));
    databaseIdProviderElement(root.evalNode("databaseIdProvider"));
    typeHandlerElement(root.evalNode("typeHandlers"));
    // 獲取mappers標(biāo)簽下的內(nèi)容
    mapperElement(root.evalNode("mappers"));
  } catch (Exception e) {
    throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
  }
}

可以看到,上面的方法會(huì)分別獲取配置文件中的各種類型的標(biāo)簽內(nèi)容,然后執(zhí)行相應(yīng)的處理邏輯,實(shí)際上也是我們通用的一種處理XML文件的解析處理過(guò)程。接下來(lái),我們選擇mappers標(biāo)簽,來(lái)重點(diǎn)看看其中的處理邏輯,也就是mapperElement方法:

private void mapperElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      // 處理package子節(jié)點(diǎn)
      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) {
          // 處理mapper子節(jié)點(diǎn)的resource屬性
          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) {
          // 處理mapper子節(jié)點(diǎn)的url屬性
          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) {
          // 處理mapper子節(jié)點(diǎn)的class屬性
          Class<?> mapperInterface = Resources.classForName(mapperClass);
          configuration.addMapper(mapperInterface);
        } else {
          // 如果設(shè)置了多個(gè)屬性,則提示報(bào)錯(cuò) 
          throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
        }
      }
    }
  }
}

上面的處理邏輯很清晰了,XNode parent即是<mappers>標(biāo)簽,首先利用getChildren方法來(lái)獲取下面的子節(jié)點(diǎn)。判斷如果是<package>子標(biāo)簽,則獲取其name屬性值,并調(diào)用configuration.addMappers進(jìn)行處理。如果不是,則進(jìn)入else分支,來(lái)處理<mapper>標(biāo)簽里的屬性。 本文初介紹過(guò)<mapper>標(biāo)簽支持的屬性值,且只能設(shè)置其中的一個(gè),這里就找到了代碼的佐證。

在上面的代碼中可以發(fā)現(xiàn),對(duì)于不同的標(biāo)簽和屬性,分別有兩種處理方式,一種是調(diào)用configuration.addMappers方法,另一種是調(diào)用mapperParser.parse(),接下來(lái)我們分別來(lái)看一下這兩種方法的處理邏輯。

首先來(lái)看一下configuration.addMappers

public void addMappers(String packageName) {
  mapperRegistry.addMappers(packageName);
}

/**
 * @since 3.2.2
 */
public void addMappers(String packageName) {
  addMappers(packageName, Object.class);
}

/**
 * @since 3.2.2
 */
public void addMappers(String packageName, Class<?> superType) {
  ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
  resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
  Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
  for (Class<?> mapperClass : mapperSet) {
    addMapper(mapperClass);
  }
}

層層調(diào)用addMappers方法,在上面第三個(gè)重載方法中,創(chuàng)建了一個(gè)ResolverUtil實(shí)例,ResolverUtil用來(lái)定位給定類路徑中的可用且滿足任意條件的類。 因此,resolverUtil.find(new ResolverUtil.IsA(superType), packageName) 實(shí)際上就是找到給定類路徑packageName下的所有可用類:

public ResolverUtil<T> find(Test test, String packageName) {
  // 將packageName中的.轉(zhuǎn)換成/
  String path = getPackagePath(packageName);

  try {
    // 掃描從所提供的包開始到子包的類
    List<String> children = VFS.getInstance().list(path);
    for (String child : children) {
      if (child.endsWith(".class")) {
        // 如果URL資源描述符以.class結(jié)尾,則判斷是否加入到matches集合中
        addIfMatching(test, child);
      }
    }
  } catch (IOException ioe) {
    log.error("Could not read package: " + packageName, ioe);
  }

  return this;
}

// 當(dāng)且僅當(dāng)提供的測(cè)試批準(zhǔn)時(shí),將所提供的完全限定類名指定的類添加到已解析類集中。
protected void addIfMatching(Test test, String fqn) {
  try {
    String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
    // 獲取類加載器
    ClassLoader loader = getClassLoader();
    if (log.isDebugEnabled()) {
      log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
    }

    // 利用類加載器加載全限定類名指定的類
    Class<?> type = loader.loadClass(externalName);
    if (test.matches(type)) {
      // 如果test驗(yàn)證條件匹配后,則將該類加入到matches集合中
      // 這里的test.matches實(shí)際上就是判斷type對(duì)應(yīng)的類的父類是不是Object類
      matches.add((Class<T>) type);
    }
  } catch (Throwable t) {
    log.warn("Could not examine class '" + fqn + "'" + " due to a " +
        t.getClass().getName() + " with message: " + t.getMessage());
  }
}

上面我們花費(fèi)了一定篇幅來(lái)細(xì)致地分析了addMappers方法中實(shí)現(xiàn)的核心邏輯,目前我們可以知道,resolverUtil.getClasses()方法就是獲取到<package>標(biāo)簽中name屬性指定的包名及其子包下的所有類,然后進(jìn)行遍歷,對(duì)每個(gè)類執(zhí)行addMapper方法:

public <T> void addMapper(Class<T> type) {
  // 如果該類是一個(gè)接口類
  if (type.isInterface()) {
    // 判斷knownMappers中是否已經(jīng)有當(dāng)前映射接口
    // Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>(); 
    // knownMappers是一個(gè)map存儲(chǔ)結(jié)構(gòu),key為映射接口Class對(duì)象,value為MapperProxyFactory
    // MapperProxyFactory為映射接口對(duì)應(yīng)的動(dòng)態(tài)代理工廠
    if (hasMapper(type)) {
      throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
    }
    boolean loadCompleted = false;
    try {
      // knownMappers中存儲(chǔ)每個(gè)映射接口對(duì)應(yīng)的動(dòng)態(tài)代理工廠
      knownMappers.put(type, new MapperProxyFactory<>(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.
      // 依靠MapperAnnotationBuilder來(lái)完成映射文件和映射接口中的Sql解析
      // 先解析映射文件,再解析映射接口
      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
      parser.parse();
      loadCompleted = true;
    } finally {
      if (!loadCompleted) {
        knownMappers.remove(type);
      }
    }
  }
}

上面代碼中最重要的就是我們發(fā)現(xiàn),MyBatis在解析配置文件的過(guò)程中,針對(duì)給定包名下的每個(gè)接口類,都生成了一個(gè)相應(yīng)的MapperProxyFactory實(shí)例,并保存在knownMapeprs的HashMap中。 顧名思義,MapperProxyFactory就是映射接口的動(dòng)態(tài)代理工廠,負(fù)責(zé)為對(duì)應(yīng)的映射接口生成動(dòng)態(tài)代理類。這里動(dòng)態(tài)代理的生成邏輯我們暫且按下不表,先繼續(xù)看一下上面對(duì)映射文件和映射接口中的SQL進(jìn)行解析的MapeprAnnotationBuilder類,該類中包含了下面一些屬性:

private final Configuration configuration;
private final MapperBuilderAssistant assistant;
private final Class<?> type;

可知,每個(gè)MapperAnnotationBuilder實(shí)例都會(huì)對(duì)應(yīng)一個(gè)映射接口類,且持有一個(gè)全局唯一的Configuration類,目的是為了將parse方法中對(duì)映射配置文件的SQL解析豐富進(jìn)該Configuration中。接下來(lái),我們就繼續(xù)來(lái)探究一下parse()方法中具體執(zhí)行了什么:

public void parse() {
  String resource = type.toString();
  // 判斷映射接口是否已經(jīng)被解析過(guò),沒(méi)解析過(guò)才會(huì)繼續(xù)往下執(zhí)行
  if (!configuration.isResourceLoaded(resource)) {
    // 解析映射配置文件的內(nèi)容,并豐富進(jìn)Configuration中
    loadXmlResource();
    // 將當(dāng)前映射接口添加到緩存中,以表示當(dāng)前映射接口已經(jīng)被解析過(guò)
    configuration.addLoadedResource(resource);
    assistant.setCurrentNamespace(type.getName());
    parseCache();
    parseCacheRef();
    // 遍歷接口類中的所有方法,目的是為了處理接口方法中利用注解方式添加的SQL語(yǔ)句
    Method[] methods = type.getMethods();
    for (Method method : methods) {
      try {
        // issue #237
        if (!method.isBridge()) {
          parseStatement(method);
        }
      } catch (IncompleteElementException e) {
        configuration.addIncompleteMethod(new MethodResolver(this, method));
      }
    }
  }
  parsePendingMethods();
}

按照parse()方法的執(zhí)行流程,會(huì)先解析映射配置文件XML中的配置SQL語(yǔ)句,然后再解析接口方法中利用注解方法配置的SQL語(yǔ)句。這里以解析映射文件為例,先來(lái)看一下loadXmlResource()方法的實(shí)現(xiàn):

private void loadXmlResource() {
  // Spring may not know the real resource name so we check a flag
  // to prevent loading again a resource twice
  // this flag is set at XMLMapperBuilder#bindMapperForNamespace
  if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
    // 根據(jù)接口類的全限定類名,拼接上.xml來(lái)得到相應(yīng)的映射配置文件
    // 這也就是為什么如果是<package>標(biāo)簽,需要映射配置文件和映射接口在同一目錄
    String xmlResource = type.getName().replace('.', '/') + ".xml";
    // #1347
    InputStream inputStream = type.getResourceAsStream("/" + xmlResource);
    if (inputStream == null) {
      // Search XML mapper that is not in the module but in the classpath.
      try {
        inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
      } catch (IOException e2) {
        // ignore, resource is not required
      }
    }
    if (inputStream != null) {
      XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
      // 解析映射配置文件
      xmlParser.parse();
    }
  }
}

在上面的loadXmlResource方法中我們又找到了一處本文初介紹的<package>標(biāo)簽配置時(shí)規(guī)范的代碼佐證,即為什么要求映射文件與映射接口同名且同目錄。同樣的,對(duì)于XML映射配置文件,MyBatis將其轉(zhuǎn)換成字節(jié)輸入流,并同樣利用XMLMapperBuilder類進(jìn)行解析。這里對(duì)XML文件的解析也是我們可以學(xué)習(xí)的一點(diǎn),日后在其他地方對(duì)XML文件的解析都可以參照這一流程。

在這里插入圖片描述

另外需要特別注意的一點(diǎn)是,如上圖所示,解析核心配置文件和映射配置文件的解析類分別為XMLConfigBuilderXMLMapperBuilder,均繼承自BaseBuilder。而BaseBuilder中持有全局唯一的Configuration,所以兩者對(duì)配置文件的解析均會(huì)豐富進(jìn)Configuration。

繼續(xù)進(jìn)入xmlParser.parse()方法中,來(lái)看一下是如何對(duì)映射配置文件進(jìn)行解析的:

public void parse() {
  if (!configuration.isResourceLoaded(resource)) {
    // 解析映射配置文件的mapper根標(biāo)簽
    configurationElement(parser.evalNode("/mapper"));
    configuration.addLoadedResource(resource);
    bindMapperForNamespace();
  }

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

繼續(xù)看configurationElement的實(shí)現(xiàn):

private void configurationElement(XNode context) {
  try {
    // 獲取<mapper>標(biāo)簽的namespace屬性
    String namespace = context.getStringAttribute("namespace");
    if (namespace == null || namespace.equals("")) {
      throw new BuilderException("Mapper's namespace cannot be empty");
    }
    builderAssistant.setCurrentNamespace(namespace);
    // 解析MyBatis一級(jí)/二級(jí)緩存相關(guān)的標(biāo)簽
    cacheRefElement(context.evalNode("cache-ref"));
    cacheElement(context.evalNode("cache"));
    // 解析<parameterMap>標(biāo)簽,生成ParameterMap并緩存到Configuration
    parameterMapElement(context.evalNodes("/mapper/parameterMap"));
    // 解析<resultMap>標(biāo)簽,生成ResultMap并緩存到Configuration
    resultMapElements(context.evalNodes("/mapper/resultMap"));
    // 將<sql>標(biāo)簽對(duì)應(yīng)的SQL片段保存到sqlFragments緩存中
    sqlElement(context.evalNodes("/mapper/sql"));
    // 解析<selecct> 、<insert>、<update>和<delete>標(biāo)簽
    // 生成MappedStatement并緩存到Configuration
    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);
  }
}

通過(guò)上面的方法可以發(fā)現(xiàn),解析XML文件來(lái)說(shuō),實(shí)際上就是xPath獲取到每個(gè)需要分析的標(biāo)簽,然后將各個(gè)子標(biāo)簽解析成相應(yīng)的類。在MyBatis中,上面對(duì)每個(gè)子標(biāo)簽的解析結(jié)果,最后都會(huì)緩存到Configuration中。通常,在映射文件的<mapper>標(biāo)簽下,常用的子標(biāo)簽為<parameterMap><resultMap>、<select><insert>、<update>、<delete>。下面著重分析一下buildStatementFromContext方法,來(lái)看一下MyBatis是如何對(duì)上述標(biāo)簽進(jìn)行解析的。

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) {
  // 每一個(gè)<select>、<insert>、<update>和<delete>標(biāo)簽均會(huì)被創(chuàng)建一個(gè)MappedStatement
  // 每個(gè)MappedStatement會(huì)存放在Configuration的mappedStatements緩存中
  // mappedStatements是一個(gè)map,鍵為映射接口全限定名+"."+標(biāo)簽id,值為MappedStatement  
  for (XNode context : list) {
    // 上面的每個(gè)標(biāo)簽都會(huì)創(chuàng)建一個(gè)XMLStatementBuilder來(lái)進(jìn)行解析
    final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
    try {
      statementParser.parseStatementNode();
    } catch (IncompleteElementException e) {
      configuration.addIncompleteStatement(statementParser);
    }
  }
}

對(duì)于每一個(gè)<select><insert>、<update><delete>標(biāo)簽,均會(huì)創(chuàng)建一個(gè)XMlStatementBuilder來(lái)進(jìn)行解析并生成MappedStatement,同樣,看一下XMlStatementBuilder的類圖,如下所示:

在這里插入圖片描述

XMLStatementBuilder中持有<select>,<insert>,<update>和<delete>標(biāo)簽對(duì)應(yīng)的節(jié)點(diǎn)XNode,以及幫助創(chuàng)建MappedStatement并豐富進(jìn)ConfigurationMapperBuilderAssistant類。下面看一下XMLStatementBuilderparseStatementNode() 方法。

public void parseStatementNode() {
  // 獲取標(biāo)簽id
  String id = context.getStringAttribute("id");
  String databaseId = context.getStringAttribute("databaseId");

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

  String nodeName = context.getNode().getNodeName();
  // 獲取標(biāo)簽類型,例如SELECT,INSERT等
  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
  // 如果使用了<include>標(biāo)簽,則將<include>標(biāo)簽替換為匹配的<sql>標(biāo)簽中的sql片段
  // 匹配規(guī)則是在Configuration中根據(jù)namespace+"."+refid去匹配<sql>標(biāo)簽
  XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
  includeParser.applyIncludes(context.getNode());

  // 獲取輸入?yún)?shù)類型
  String parameterType = context.getStringAttribute("parameterType");
  Class<?> parameterTypeClass = resolveClass(parameterType);

  // 獲取LanguageDriver以支持實(shí)現(xiàn)動(dòng)態(tài)sql
  // 這里獲取到的實(shí)際上為XMLLanguageDriver
  String lang = context.getStringAttribute("lang");
  LanguageDriver langDriver = getLanguageDriver(lang);

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

  // Parse the SQL (pre: <selectKey> and <include> were parsed and removed)
  // 獲取KeyGenerator
  KeyGenerator keyGenerator;
  String keyStatementId = id + SelectKeyGenerator.SELECT_KEY_SUFFIX;
  keyStatementId = builderAssistant.applyCurrentNamespace(keyStatementId, true);
  if (configuration.hasKeyGenerator(keyStatementId)) {
    keyGenerator = configuration.getKeyGenerator(keyStatementId);
  } else {
    // 如果緩存中獲取不到,則根據(jù)useGeneratedKeys的配置決定是否使用KeyGenerator
    // 如果要使用,則MyBatis中使用的KeyGenerator為Jdbc3KeyGenerator
    keyGenerator = context.getBooleanAttribute("useGeneratedKeys",
        configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType))
        ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE;
  }

  // 通過(guò)XMLLanguateDriver創(chuàng)建SqlSource,可以理解為sql語(yǔ)句
  // 如果使用到了<if>、<foreach>等標(biāo)簽進(jìn)行動(dòng)態(tài)sql語(yǔ)句的拼接,則創(chuàng)建出來(lái)的SqlSource為DynamicSqlSource
  SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
  StatementType statementType = StatementType.valueOf(context.getStringAttribute("statementType", StatementType.PREPARED.toString()));
  // 獲取標(biāo)簽上的各種屬性
  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");

  // 根據(jù)上面獲取到的參數(shù),創(chuàng)建MappedStatement并添加到Configuration中
  builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
      fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
      resultSetTypeEnum, flushCache, useCache, resultOrdered,
      keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}

parseStatementNode() 方法整體流程稍長(zhǎng),總結(jié)概括起來(lái)該方法做了如下幾件事情。

  • 將<include>標(biāo)簽替換為其指向的SQL片段;
  • 如果未使用動(dòng)態(tài)SQL,則創(chuàng)建RawSqlSource以保存SQL語(yǔ)句,如果使用了動(dòng)態(tài)SQL(例如使用了<if>,<foreach>等標(biāo)簽),則創(chuàng)建DynamicSqlSource以支持SQL語(yǔ)句的動(dòng)態(tài)拼接;
  • 獲取<select>,<insert>,<update>和<delete>標(biāo)簽上的屬性;
  • 將獲取到的SqlSource以及標(biāo)簽上的屬性傳入MapperBuilderAssistantaddMappedStatement() 方法,以創(chuàng)建MappedStatement并添加到Configuration中。

MapperBuilderAssistant是最終創(chuàng)建MappedStatement以及將MappedStatement添加到Configuration的處理類,其addMappedStatement() 方法如下所示。

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

  // 拼接出MappedStatement的唯一標(biāo)識(shí),規(guī)則是namespace + ". " + id
  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);
  }
  
  // 創(chuàng)建MappedStatment
  MappedStatement statement = statementBuilder.build();
  // 將MappedStatement添加到Configuration中
  configuration.addMappedStatement(statement);
  return statement;
}

至此,我們終于在這里發(fā)現(xiàn)了MyBatis是如何解析映射配置文件,生成MappedStatement,并將其加載到Configuration類中。實(shí)際上,解析<parameterMap>標(biāo)簽,解析<resultMap>標(biāo)簽的大體流程和上面基本一致,最終都是借助MapperBuilderAssistant生成對(duì)應(yīng)的類(例如ParameterMap,ResultMap)然后再緩存到Configuration中,且每種解析生成的類在對(duì)應(yīng)緩存中的唯一標(biāo)識(shí)為namespace + “.” + 標(biāo)簽id

最后,回到本小結(jié)開頭的XMLConfigBuilder中的mapperElement方法,目前我們已經(jīng)將方法內(nèi)部的邏輯大致探究清晰,主要的工作就是根據(jù)配置文件中的標(biāo)簽下的子標(biāo)簽的不同( 或 ),以及根據(jù)子標(biāo)簽的屬性不同,獲取到所配置位置的映射配置文件,再使用XMLMapperBuilder類進(jìn)行統(tǒng)一解析。最后,將解析得到的結(jié)果封裝成MappedStatement對(duì)象,添加到Configuration類。

更為具體的解析細(xì)節(jié),大家有興趣可以閱讀源碼進(jìn)行深入的分析,最后,我們利用一個(gè)示意圖來(lái)對(duì)上述的MyBatis加載配置文件的流程進(jìn)行一個(gè)總結(jié):

在這里插入圖片描述

 到此這篇關(guān)于Mybatis核心配置文件加載流程詳解的文章就介紹到這了,更多相關(guān)Mybatis核心配置文件加載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java并發(fā)編程信號(hào)量Semapher

    Java并發(fā)編程信號(hào)量Semapher

    這篇文章主要介紹了Java并發(fā)編程信號(hào)量Semapher,Semapher信號(hào)量也是Java中的一個(gè)同步器,下文關(guān)于信號(hào)量Semapher的更多內(nèi)容介紹,需要的小伙伴可以參考下面文章
    2022-04-04
  • 構(gòu)建Maven多模塊項(xiàng)目的方法

    構(gòu)建Maven多模塊項(xiàng)目的方法

    這篇文章主要介紹了構(gòu)建Maven多模塊項(xiàng)目的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-08-08
  • Spring Security組件一鍵接入驗(yàn)證碼登錄和小程序登錄的詳細(xì)過(guò)程

    Spring Security組件一鍵接入驗(yàn)證碼登錄和小程序登錄的詳細(xì)過(guò)程

    這篇文章主要介紹了Spring Security 一鍵接入驗(yàn)證碼登錄和小程序登錄,簡(jiǎn)單介紹一下這個(gè)插件包的相關(guān)知識(shí),本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧
    2022-04-04
  • Springboot 如何實(shí)現(xiàn)filter攔截token驗(yàn)證和跨域

    Springboot 如何實(shí)現(xiàn)filter攔截token驗(yàn)證和跨域

    這篇文章主要介紹了Springboot 如何實(shí)現(xiàn)filter攔截token驗(yàn)證和跨域操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 優(yōu)惠券優(yōu)惠的思路以及實(shí)踐

    優(yōu)惠券優(yōu)惠的思路以及實(shí)踐

    本文主要介紹了優(yōu)惠券優(yōu)惠的思路以及實(shí)踐。具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-02-02
  • 利用JWT如何實(shí)現(xiàn)對(duì)API的授權(quán)訪問(wèn)詳解

    利用JWT如何實(shí)現(xiàn)對(duì)API的授權(quán)訪問(wèn)詳解

    這篇文章主要給大家介紹了關(guān)于利用JWT如何實(shí)現(xiàn)對(duì)API的授權(quán)訪問(wèn)的相關(guān)資料,需要的朋友可以參考下
    2018-09-09
  • Hystrix?Turbine聚合監(jiān)控的實(shí)現(xiàn)詳解

    Hystrix?Turbine聚合監(jiān)控的實(shí)現(xiàn)詳解

    微服務(wù)架構(gòu)下,?個(gè)微服務(wù)往往部署多個(gè)實(shí)例,如果每次只能查看單個(gè)實(shí)例的監(jiān)控,就需要經(jīng)常切換很不?便,在這樣的場(chǎng)景下,我們可以使??Hystrix?Turbine?進(jìn)?聚合監(jiān)控,它可以把相關(guān)微服務(wù)的監(jiān)控?cái)?shù)據(jù)聚合在?起,便于查看
    2022-09-09
  • java實(shí)現(xiàn)去除ArrayList重復(fù)字符串

    java實(shí)現(xiàn)去除ArrayList重復(fù)字符串

    本文主要介紹了java實(shí)現(xiàn)去除ArrayList重復(fù)字符串,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-09-09
  • java:程序包org.bouncycastle.jce.provider不存在問(wèn)題及解決

    java:程序包org.bouncycastle.jce.provider不存在問(wèn)題及解決

    這篇文章主要介紹了java:程序包org.bouncycastle.jce.provider不存在問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • java實(shí)現(xiàn)上傳網(wǎng)絡(luò)圖片到微信臨時(shí)素材

    java實(shí)現(xiàn)上傳網(wǎng)絡(luò)圖片到微信臨時(shí)素材

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)上傳網(wǎng)絡(luò)圖片到微信臨時(shí)素材,網(wǎng)絡(luò)圖片上傳到微信服務(wù)器,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-07-07

最新評(píng)論