1. 程式人生 > >MyBatis官方教程及源代碼解析——mapper映射文件

MyBatis官方教程及源代碼解析——mapper映射文件

getparent execute 執行 rtb 再處理 catch pro ttr 刪除

緩存

1.官方文檔

MyBatis 包括一個非常強大的查詢緩存特性,它能夠非常方便地配置和定制。

MyBatis 3 中的緩存實現的非常多改進都已經實現了,使得它更加強大並且易於配置。

默認情況下是沒有開啟緩存的,除了局部的session 緩存,能夠增強變現並且處理循環 依賴也是必須的。要開啟二級緩存,你須要在你的 SQL 映射文件裏加入一行:

<cache/>

字面上看就是這樣。

這個簡單語句的效果例如以下:

·????????映射語句文件裏的全部 select語句將會被緩存。

·????????映射語句文件裏的全部 insert,update和 delete 語句會刷新緩存。

·????????緩存會使用 Least Recently Used(LRU,近期最少使用的)算法來收回。

·????????依據時間表(比方 no Flush Interval,沒有刷新間隔), 緩存不會以不論什麽時間順序 來刷新。

·????????緩存會存儲列表集合或對象(不管查詢方法返回什麽)的 1024 個引用。

·????????緩存會被視為是 read/write(可讀/可寫)的緩存,意味著對象檢索不是共享的,而 且能夠安全地被調用者改動,而不幹擾其它調用者或線程所做的潛在改動。

全部的這些屬性都能夠通過緩存元素的屬性來改動。

比方:

<cache
? eviction="FIFO"
? flushInterval="60000"
? size="512"
? readOnly="true"/>

這個更高級的配置創建了一個 FIFO 緩存,並每隔 60 秒刷新,存數結果對象或列表的 512 個引用,並且返回的對象被覺得是僅僅讀的,因此在不同線程中的調用者之間改動它們會 導致沖突。

可用的收回策略有:

·????????LRU?–近期最少使用的:移除最長時間不被使用的對象。

·????????FIFO?–先進先出:按對象進入緩存的順序來移除它們。

·????????SOFT?–軟引用:移除基於垃圾回收器狀態和軟引用規則的對象。

·????????WEAK?–弱引用:更積極地移除基於垃圾收集器狀態和弱引用規則的對象。

默認的是 LRU

flushInterval(刷新間隔)能夠被設置為隨意的正整數,並且它們代表一個合理的毫秒 形式的時間段。默認情況是不設置,也就是沒有刷新間隔,緩存僅僅調用語句時刷新。

size(引用數目)能夠被設置為隨意正整數,要記住你緩存的對象數目和你執行環境的 可用內存資源數目。

默認值是 1024。

readOnly(僅僅讀)屬性能夠被設置為 true 或 false。

僅僅讀的緩存會給全部調用者返回緩 存對象的同樣實例。因此這些對象不能被改動。這提供了非常重要的性能優勢。可讀寫的緩存會返回緩存對象的拷貝(通過序列化) 。這會慢一些,可是安全,因此默認是 false。


2.源代碼解析

緩存的解析比較簡單。mybatis依據配置生成一個cache對象,並存入configuration。每一個映射配置文件僅僅能有一個cache,配置多個時僅僅有第一個生效

//XMLMapperBuilder類
private void cacheElement(XNode context) throws Exception {
if (context != null) {
      //獲取配置
      String type = context.getStringAttribute("type", "PERPETUAL");
      Class<?

extends Cache> typeClass = typeAliasRegistry.resolveAlias(type); String eviction = context.getStringAttribute("eviction", "LRU"); Class<? extends Cache> evictionClass = typeAliasRegistry.resolveAlias(eviction); Long flushInterval = context.getLongAttribute("flushInterval"); Integer size = context.getIntAttribute("size"); boolean readWrite = !context.getBooleanAttribute("readOnly", false); boolean blocking = context.getBooleanAttribute("blocking", false); Properties props = context.getChildrenAsProperties(); //由builderAssistant對象生成 builderAssistant.useNewCache(typeClass, evictionClass, flushInterval, size, readWrite, blocking, props); } } //MapperBuilderAssistant類 public Cache useNewCache(Class<?

extends Cache> typeClass, Class<? extends Cache> evictionClass, Long flushInterval, Integer size, boolean readWrite, boolean blocking, Properties props) { 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(); //將cache存入configuration configuration.addCache(cache); //置為當前cache currentCache = cache; return cache; }


除了定義一個新的緩存,我們還能夠直接使用其它映射文件配置的緩存,這就利用到了cache-ref

<cache-ref namespace="com.someone.application.data.SomeMapper"/>

要註意的是<cache-ref>的解析在<cache>之前,所以currentCache 對象會選擇後者

private void cacheRefElement(XNode context) {
if (context != null) {
      //依照兩個映射文件的名空間存入configuration
      configuration.addCacheRef(builderAssistant.getCurrentNamespace(), context.getStringAttribute("namespace"));
      CacheRefResolver cacheRefResolver = new CacheRefResolver(builderAssistant, context.getStringAttribute("namespace"));
      try {
//這裏盡管定義了cacheRefResolver 對象,但終於調用的是MapperBuilderAssistant類的useCacheRef方法
        cacheRefResolver.resolveCacheRef();
      } catch (IncompleteElementException e) {
        configuration.addIncompleteCacheRef(cacheRefResolver);
      }
    }
  }
public Cache useCacheRef(String namespace) {
    if (namespace == null) {
      throw new BuilderException("cache-ref element requires a namespace attribute.");
    }
    try {
      unresolvedCacheRef = true;
      Cache cache = configuration.getCache(namespace);
      //cache找不到的一種可能是相應的映射文件還未解析,這樣的時候會拋出異常
      if (cache == null) {
        throw new IncompleteElementException("No cache for namespace ‘" + namespace + "‘ could be found.");
      }
      //假設找到相應cache則currentCache 會置為該對象
      currentCache = cache;
      unresolvedCacheRef = false;
      return cache;
    } catch (IllegalArgumentException e) {
      throw new IncompleteElementException("No cache for namespace ‘" + namespace + "‘ could be found.", e);
    }
  }

Sql語句塊

1.官方文檔

這個元素能夠被用來定義可重用的 SQL 代碼段,能夠包括在其它語句中。它能夠被靜態地(在載入參數) 參數化. 不同的屬性值通過包括的實例變化. 比方:

<sql id="userColumns"> ${alias}.id,${alias}.username,${alias}.password </sql>

這個 SQL 片段能夠被包括在其它語句中,比如:

<select id="selectUsers" resultType="map">
? select
??? <include refid="userColumns"><property name="alias" value="t1"/></include>,
??? <include refid="userColumns"><property name="alias" value="t2"/></include>
? from some_table t1
??? cross join some_table t2</select>

屬性值能夠用於包括的refid屬性或者包括的字句裏面的屬性值,比如:

<sql id="sometable">
? ${prefix}Table</sql>
<sql id="someinclude">
? from
??? <include refid="${include_target}"/></sql>
<select id="select" resultType="map">
? select
??? field1, field2, field3
? <include refid="someinclude">
??? <property name="prefix" value="Some"/>
??? <property name="include_target" value="sometable"/>
? </include></select>

2.源代碼解析

Sql語句塊和映射語句在解析的時候會依據DatabaseId來進行區分,假設同一時候找到帶有?databaseId?和不帶?databaseId?的同樣語句,則後者會被舍棄。利用這點,在配置語句的時候能夠為不同數據庫配置不同的語句。

//XMLMapperBuilder類中
private void sqlElement(List<XNode> list) throws Exception {
//這裏的配置取自配置文件裏的databaseIdProvider
    if (configuration.getDatabaseId() != null) {
      sqlElement(list, configuration.getDatabaseId());
    }
    sqlElement(list, null);
  }

  private void sqlElement(List<XNode> list, String requiredDatabaseId) throws Exception {
    for (XNode context : list) {
      String databaseId = context.getStringAttribute("databaseId");
      String id = context.getStringAttribute("id");
      id = builderAssistant.applyCurrentNamespace(id, false);
      //在此處對databaseId配置和當前數據庫進行匹配
      if (databaseIdMatchesCurrent(id, databaseId, requiredDatabaseId)) {
//終於依據ID將整個節點存入
        sqlFragments.put(id, context);
      }
    }
  }
  
  private boolean databaseIdMatchesCurrent(String id, String databaseId, String requiredDatabaseId) {
//假設有配置databaseIdProvider,則兩者必須一致
    if (requiredDatabaseId != null) {
      if (!requiredDatabaseId.equals(databaseId)) {
        return false;
      }
} else {
  //假設沒有配置databaseIdProvider,則不須要配置databaseId 
      if (databaseId != null) {
        return false;
      }
      // 假設存在同樣ID且databaseId不為空。則省略
      if (this.sqlFragments.containsKey(id)) {
        XNode context = this.sqlFragments.get(id);
        if (context.getStringAttribute("databaseId") != null) {
          return false;
        }
      }
    }
    return true;
  }

在最後sql代碼塊將整個節點都存入Map中,這樣做是由於sql能夠實現動態復用,因此每次都必須又一次解析sql代碼塊的值,這些在接下來映射語句的解析部分完畢。


映射語句

映射語句是Mapper配置中比較復雜的一部分。一方面能夠嵌入sql語句塊,還有一方面還有動態Sql。

//XMLMapperBuilder類中
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) {
      final XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, context, requiredDatabaseId);
      try {
        //這裏又由XMLStatementBuilder類來進行解析
        statementParser.parseStatementNode();
      } catch (IncompleteElementException e) {
        configuration.addIncompleteStatement(statementParser);
      }
    }
  }
//XMLStatementBuilder類中
public void parseStatementNode() {
    String id = context.getStringAttribute("id");
    String databaseId = context.getStringAttribute("databaseId");

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

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

    String nodeName = context.getNode().getNodeName();
SqlCommandType sqlCommandType = SqlCommandType.valueOf(nodeName.toUpperCase(Locale.ENGLISH));
//這裏推斷是不是查詢語句。影響到後面flushCache和userCache的默認值
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
    boolean flushCache = context.getBooleanAttribute("flushCache", !isSelect);
    boolean useCache = context.getBooleanAttribute("useCache", isSelect);
    boolean resultOrdered = context.getBooleanAttribute("resultOrdered", false);

    //1.先處理sql代碼塊(include)
    XMLIncludeTransformer includeParser = new XMLIncludeTransformer(configuration, builderAssistant);
    includeParser.applyIncludes(context.getNode());

    //2.再處理selectKey並移除
    processSelectKeyNodes(id, parameterTypeClass, langDriver);
    
    //3.最後解析SQL語句
    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    String resultSets = context.getStringAttribute("resultSets");
    String keyProperty = context.getStringAttribute("keyProperty");
    String keyColumn = context.getStringAttribute("keyColumn");
    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))
          ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
    }

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

先來看<include>的解析。在官方文檔裏面能夠看到<include>中包括了<propery>子節點。

用戶能夠為<propery>配置不同的值來實現動態的復用,假設沒有對<propery>進行配置,Mybatis會從XML配置文件裏面尋找

public void applyIncludes(Node source) {
Properties variablesContext = new Properties();
//獲取XML配置文件裏的property值
    Properties configurationVariables = configuration.getVariables();
    if (configurationVariables != null) {
      variablesContext.putAll(configurationVariables);
    }
    applyIncludes(source, variablesContext);
  }
  private void applyIncludes(Node source, final Properties variablesContext) {
//針對<include>進行解析
    if (source.getNodeName().equals("include")) {
      //這裏新定義fullContext對象,保證在一個解析過程中使用同一套值      
Properties fullContext;
      String refid = getStringAttribute(source, "refid");
      //對refid進行解析(比如refid="${include_target}"的形式)
      refid = PropertyParser.parse(refid, variablesContext);
      Node toInclude = findSqlFragment(refid);
      //這裏對<property>進行解析並返回結果
      Properties newVariablesContext = getVariablesContext(source, variablesContext);
      //依據解析結果使用不同的值
      if (!newVariablesContext.isEmpty()) {
        // merge contexts
        fullContext = new Properties();
        fullContext.putAll(variablesContext);
        fullContext.putAll(newVariablesContext);
      } else {
        // no new context - use inherited fully
        fullContext = variablesContext;
      }
      //針對Sql代碼塊解析,toInclude是<sql>節點
      applyIncludes(toInclude, fullContext);
      if (toInclude.getOwnerDocument() != source.getOwnerDocument()) {
        toInclude = source.getOwnerDocument().importNode(toInclude, true);
      }
      //將<include>替換成相應<sql>
      source.getParentNode().replaceChild(toInclude, source);
      while (toInclude.hasChildNodes()) {
//插入<sql>節點解析後的sql語句
        toInclude.getParentNode().insertBefore(toInclude.getFirstChild(), toInclude);
      }
      //最後移除<sql>節點
      toInclude.getParentNode().removeChild(toInclude);
}else if (source.getNodeType() == Node.ELEMENT_NODE) {
      NodeList children = source.getChildNodes();
      for (int i=0; i<children.getLength(); i++) {
        applyIncludes(children.item(i), variablesContext);
      }
    } else if (source.getNodeType() == Node.ATTRIBUTE_NODE && !variablesContext.isEmpty()) {
      // replace variables in all attribute values
      source.setNodeValue(PropertyParser.parse(source.getNodeValue(), variablesContext));
    } else if (source.getNodeType() == Node.TEXT_NODE && !variablesContext.isEmpty()) {
      // replace variables ins all text nodes
      source.setNodeValue(PropertyParser.parse(source.getNodeValue(), variablesContext));
}
  }
以上過程終於將<include>替換成相應的sql語句。


接下來是<selectKey>的解析。我們能夠將其視為一種特殊的映射語句。終於結果保存在configuration的keyGenerators中
private void processSelectKeyNodes(String id, Class<?

> parameterTypeClass, LanguageDriver langDriver) { List<XNode> selectKeyNodes = context.evalNodes("selectKey"); //也須要推斷databaseId if (configuration.getDatabaseId() != null) { parseSelectKeyNodes(id, selectKeyNodes, parameterTypeClass, langDriver, configuration.getDatabaseId()); } parseSelectKeyNodes(id, selectKeyNodes, parameterTypeClass, langDriver, null); //解析後刪除節點 removeSelectKeyNodes(selectKeyNodes); } private void parseSelectKeyNodes(String parentId, List<XNode> list, Class<?> parameterTypeClass, LanguageDriver langDriver, String skRequiredDatabaseId) { for (XNode nodeToHandle : list) { String id = parentId + SelectKeyGenerator.SELECT_KEY_SUFFIX; String databaseId = nodeToHandle.getStringAttribute("databaseId"); if (databaseIdMatchesCurrent(id, databaseId, skRequiredDatabaseId)) { parseSelectKeyNode(id, nodeToHandle, parameterTypeClass, langDriver, databaseId); } } } private void parseSelectKeyNode(String id, XNode nodeToHandle, Class<?> parameterTypeClass, LanguageDriver langDriver, String databaseId) { String resultType = nodeToHandle.getStringAttribute("resultType"); Class<?> resultTypeClass = resolveClass(resultType); StatementType statementType = StatementType.valueOf(nodeToHandle.getStringAttribute("statementType", StatementType.PREPARED.toString())); String keyProperty = nodeToHandle.getStringAttribute("keyProperty"); String keyColumn = nodeToHandle.getStringAttribute("keyColumn"); boolean executeBefore = "BEFORE".equals(nodeToHandle.getStringAttribute("order", "AFTER")); //defaults boolean useCache = false; boolean resultOrdered = false; KeyGenerator keyGenerator = new NoKeyGenerator(); Integer fetchSize = null; Integer timeout = null; boolean flushCache = false; String parameterMap = null; String resultMap = null; ResultSetType resultSetTypeEnum = null; SqlSource sqlSource = langDriver.createSqlSource(configuration, nodeToHandle, parameterTypeClass); //這裏將<selectKey>當做一種select語句 SqlCommandType sqlCommandType = SqlCommandType.SELECT; //和映射語句一樣,<selectKey>解析成MappedStatement對象並保存, builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass, resultSetTypeEnum, flushCache, useCache, resultOrdered, keyGenerator, keyProperty, keyColumn, databaseId, langDriver, null); id = builderAssistant.applyCurrentNamespace(id, false); //這裏將解析結果保存在configuration中 MappedStatement keyStatement = configuration.getMappedStatement(id, false); configuration.addKeyGenerator(id, new SelectKeyGenerator(keyStatement, executeBefore)); }


最後是映射語句的解析

public void parseStatementNode() {
    //....省略
    
//3.最後解析SQL語句
//先是生產SqlSource對象。保存解析後的Sql語句
//該對象由langDriver產生,這部分主要是和動態Sql有關,臨時省略
    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    String resultSets = context.getStringAttribute("resultSets");
    String keyProperty = context.getStringAttribute("keyProperty");
String keyColumn = context.getStringAttribute("keyColumn");
//下面生成KeyGenerator 
KeyGenerator keyGenerator;
//keyStatementId 和<SelectKey>的id解析方式一樣,這就保證能取到前面<SelectKey>解析的結果
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))
          ? new Jdbc3KeyGenerator() : new NoKeyGenerator();
    }

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

從以上代碼能夠看出,映射語句終於會由MapperBuilderAssistant解析成MappedStatement對象。最後看看該過程怎樣實現

//MapperBuilderAssistant類
 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) {
//必須cache-ref解析完畢後才幹繼續
    if (unresolvedCacheRef) {
      throw new IncompleteElementException("Cache-ref not yet resolved");
    }

    id = applyCurrentNamespace(id, false);
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;
//最後由statementBuilder構建
    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)
        .resulSets(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;
  }




MyBatis官方教程及源代碼解析——mapper映射文件