mybatis學(xué)習(xí)-配置加載

編者按:

  1. 基于mabatis3.0.1
  2. 嘗試從架構(gòu)和產(chǎn)品設(shè)計(jì)維度重讀一點(diǎn)代碼
  3. git version hash: d929486dc250f1b9e6cf45720e59456ed8d6478b

xml配置型的配置和Mapper.xml加載

加載棧


image.png

注解型的配置和Mapper加載

1. xml和注解配置的讀取優(yōu)先順序
  • xml配置優(yōu)先
MapperAnnotationBuilder.java

public void parse() {
    String resource = type.toString();
    if (!configuration.isResourceLoaded(resource)) {
      configuration.addLoadedResource(resource);
      //優(yōu)先調(diào)用了xml配置解析
      loadXmlResource();
      assistant.setCurrentNamespace(type.getName());
      parseCache();
      parseCacheRef();
      Method[] methods = type.getMethods();
      for (Method method : methods) {
        parseResultsAndConstructorArgs(method);
        parseStatement(method);
      }
    }
  }

  private void loadXmlResource() {
    String xmlResource = type.getName().replace('.', '/') + ".xml";
    Reader xmlReader = null;
    try {
      xmlReader = Resources.getResourceAsReader(type.getClassLoader(), xmlResource);
    } catch (IOException e) {
      // ignore, resource is not required
    }
    if (xmlReader != null) {
      XMLMapperBuilder xmlParser = new XMLMapperBuilder(xmlReader, assistant.getConfiguration(), xmlResource, sqlFragments, type.getName());
      xmlParser.parse();
    }
  }
2. 配置緩存key的生成

結(jié)果如: org.mybatis.example.BlogMapper.add-Blog

private String generateResultMapName(Method method) {
    StringBuilder suffix = new StringBuilder();
    for (Class c : method.getParameterTypes()) {
      suffix.append("-");
      suffix.append(c.getSimpleName());
    }
    if (suffix.length() < 1) {
      suffix.append("-void");
    }
    return type.getName() + "." + method.getName() + suffix;
  }

//id = applyCurrentNamespace(id);
public String applyCurrentNamespace(String base) {
    if (base == null) return null;
    if (base.contains(".")) return base;
    return currentNamespace + "." + base;
  }
3. 做成只讀型

Collections.unmodifiableXXX

// lock down collections
      resultMap.resultMappings = Collections.unmodifiableList(resultMap.resultMappings);
      resultMap.idResultMappings = Collections.unmodifiableList(resultMap.idResultMappings);
      resultMap.constructorResultMappings = Collections.unmodifiableList(resultMap.constructorResultMappings);
      resultMap.propertyResultMappings = Collections.unmodifiableList(resultMap.propertyResultMappings);
      resultMap.mappedColumns = Collections.unmodifiableSet(resultMap.mappedColumns);

Resources工具類

package org.apache.ibatis.io;
/**
 * A class to simplify access to resources through the classloader.
 */
public class Resources {
  • 挺多實(shí)用方法


    image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容