MyBatis源碼分析配置解析、分析第八章

Mybatis配置解析

配置文件分析Configuration

這一章主要搞搞清楚一下幾個問題

  • 如何解析核心配置文件

  • 如何解析mapper文件

  • 如何解析mapper接口
    在這裏插入圖片描述

  • XMConfigBuilder 讀取核心配置xml

  • SqlSourceBuilder 解析sql

  • XMLScriptBuilder 讀取mapper文件

映射器的關鍵類
Configuration: Mybatis啓動初始化核心就是將所有Xml配置文件信息加載到Configuration對象中,Configuration是單例的,生命週期是應用級別。

MapperRegister: Mapper接口動態代理工廠類的註冊中心。再mybatis中通過mapperProxy實現InvocationHandler接口。MapperProxyFactory用於生成動態代理的實例對象

ResultMap: 用於解析mapper.xml文件中的resultMap節點。使用ResultMapping來封裝id,result等子元素

MappedStatement: 用於存儲mapper.xml文件的select、insert、update和delete節點,同時海包含這些節點的很重要屬性

SqlSource: mapper.xml文件中的sql語句解析成SqlSource對象,經過解析SqlSource包含的語句最終僅僅包含?佔位符,可以直接提交給數據庫執行。

源碼分析

SqlSessionFactory
org.apache.ibatis.session.SqlSessionFactoryBuilder#build(java.io.Reader, java.lang.String, java.util.Properties)

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

org.apache.ibatis.builder.xml.XMLConfigBuilder#parse

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

解析核心配置文件
org.apache.ibatis.builder.xml.XMLConfigBuilder#parseConfiguration

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對象裏面去

看點看這個節點的解析信息
org.apache.ibatis.builder.xml.XMLConfigBuilder#mapperElement

mapperElement(root.evalNode("mappers"));

org.apache.ibatis.builder.xml.XMLConfigBuilder#mapperElement 從這段代碼中我們可以看出來resource->url->class的加載順序

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

org.apache.ibatis.builder.xml.XMLMapperBuilder 開始解析Mapper.xml

XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());

org.apache.ibatis.builder.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();
  }

org.apache.ibatis.builder.xml.XMLMapperBuilder#configurationElement

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

解析緩存

org.apache.ibatis.builder.xml.XMLMapperBuilder#cacheElement

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

org.apache.ibatis.builder.MapperBuilderAssistant#useNewCache 解析文件並賦值給緩存

//通過builderAssistant創建緩存對象,並添加至configuration
  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;
  }

org.apache.ibatis.mapping.CacheBuilder#build

 public Cache build() {
	  //設置緩存的主實現類爲PerpetualCache
    setDefaultImplementations();
    //通過反射實例化PerpetualCache對象
    Cache cache = newBaseCacheInstance(implementation, id);
    setCacheProperties(cache);//根據cache節點下的<property>信息,初始化cache
    // issue #352, do not apply decorators to custom caches
    
    if (PerpetualCache.class.equals(cache.getClass())) {//如果cache是PerpetualCache的實現,則爲其添加標準的裝飾器
      for (Class<? extends Cache> decorator : decorators) {//爲cache對象添加裝飾器,這裏主要處理緩存清空策略的裝飾器
        cache = newCacheDecoratorInstance(decorator, cache);
        setCacheProperties(cache);
      }
      //通過一些屬性爲cache對象添加裝飾器
      cache = setStandardDecorators(cache);
    } else if (!LoggingCache.class.isAssignableFrom(cache.getClass())) {
      //如果cache不是PerpetualCache的實現,則爲其添加日誌的能力
      cache = new LoggingCache(cache);
    }
    return cache;
  }

// 設置完成之後添加到緩存裏面去,該對象存儲緩存對象

 protected final Map<String, Cache> caches = new StrictMap<>("Caches collection");

org.apache.ibatis.builder.MapperBuilderAssistant#useNewCache #144

 configuration.addCache(cache);

org.apache.ibatis.session.Configuration#addCache 其中cache.getId是mapper的命名空間 namespace。

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

這裏已經從緩存文件的加載解析、然後到添加到緩存裏面去基本完成已經介紹完成

數據庫裏面的字段是如何與java屬性配合使用的呢?

...............................................

第一步: 我們介紹下resultMap的數據結構是什麼呢?
org.apache.ibatis.session.Configuration#parameterMaps

/*mapper文件中配置的所有resultMap對象  key爲命名空間+ID*/
  protected final Map<String, ResultMap> resultMaps = new StrictMap<>("Result Maps collection");

org.apache.ibatis.mapping.ResultMap 存儲mapper裏面的數據結構

public class ResultMap {
  private Configuration configuration;//configuration對象

  private String id;//resultMap的id屬性
  
  private Class<?> type;//resultMap的type屬性
  
  private List<ResultMapping> resultMappings;//除discriminator節點之外的映射關係
  
  private List<ResultMapping> idResultMappings;//記錄ID或者<constructor>中idArg的映射關係
  
  private List<ResultMapping> constructorResultMappings;////記錄<constructor>標誌的映射關係
  
  private List<ResultMapping> propertyResultMappings;//記錄非<constructor>標誌的映射關係
  
  private Set<String> mappedColumns;//記錄所有有映射關係的columns字段
  
  private Set<String> mappedProperties;//記錄所有有映射關係的property字段
  
  private Discriminator discriminator;//鑑別器,對應discriminator節點
  
  private boolean hasNestedResultMaps;//是否有嵌套結果映射
  
  private boolean hasNestedQueries;////是否有嵌套查詢
  
  private Boolean autoMapping;//是否開啓了自動映射

........................................
}

存儲RequstMap的實體類對象

public class ResultMapping {

  private Configuration configuration;//引用的configuration對象
  private String property;//對應節點的property屬性
  private String column;//對應節點的column屬性
  private Class<?> javaType;//對應節點的javaType屬性
  private JdbcType jdbcType;//對應節點的jdbcType屬性
  private TypeHandler<?> typeHandler;//對應節點的typeHandler屬性
  private String nestedResultMapId;////對應節點的resultMap屬性,嵌套結果時使用

...................... 
解決關聯對象 (所謂的嵌套查詢)
private String nestedQueryId;////對應節點的select屬性,嵌套查詢時使用
private Set<String> notNullColumns;//對應節點的notNullColumn屬性
...............
  
  private String columnPrefix;//對應節點的columnPrefix屬性
  private List<ResultFlag> flags;//標誌,id 或者 constructor
  private List<ResultMapping> composites;
  private String resultSet;//對應節點的resultSet屬性
  private String foreignColumn;//對應節點的foreignColumn屬性
  private boolean lazy;//對應節點的fetchType屬性,是否延遲加載
  ....................................................................................
}
  //重點分析 :解析resultMap節點(基於數據結果去理解)----------------2-------------------
      resultMapElements(context.evalNodes("/mapper/resultMap"));

org.apache.ibatis.builder.xml.XMLMapperBuilder#resultMapElements

  //解析resultMap節點,實際就是解析sql查詢的字段與pojo屬性之間的轉化規則
  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
      }
    }
  }

org.apache.ibatis.builder.xml.XMLMapperBuilder#resultMapElement(org.apache.ibatis.parsing.XNode)

  private ResultMap resultMapElement(XNode resultMapNode) throws Exception {
    return resultMapElement(resultMapNode, Collections.<ResultMapping> emptyList());
  }

org.apache.ibatis.builder.xml.XMLMapperBuilder#resultMapElement

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

org.apache.ibatis.builder.xml.XMLMapperBuilder#buildResultMappingFromContext

 private ResultMapping buildResultMappingFromContext(XNode context, Class<?> resultType, List<ResultFlag> flags) throws Exception {
    String property;
    if (flags.contains(ResultFlag.CONSTRUCTOR)) {
      property = context.getStringAttribute("name");
    } else {
      property = context.getStringAttribute("property");
    }
    String column = context.getStringAttribute("column");
    String javaType = context.getStringAttribute("javaType");
    String jdbcType = context.getStringAttribute("jdbcType");
    String nestedSelect = context.getStringAttribute("select");
    String nestedResultMap = context.getStringAttribute("resultMap",
        processNestedResultMappings(context, Collections.<ResultMapping> emptyList()));
    String notNullColumn = context.getStringAttribute("notNullColumn");
    String columnPrefix = context.getStringAttribute("columnPrefix");
    String typeHandler = context.getStringAttribute("typeHandler");
    String resultSet = context.getStringAttribute("resultSet");
    String foreignColumn = context.getStringAttribute("foreignColumn");
    boolean lazy = "lazy".equals(context.getStringAttribute("fetchType", configuration.isLazyLoadingEnabled() ? "lazy" : "eager"));
    Class<?> javaTypeClass = resolveClass(javaType);
    @SuppressWarnings("unchecked")
    Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
    JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
    //使用建造者模式創建resultMapping對象
    return builderAssistant.buildResultMapping(resultType, property, column, javaTypeClass, jdbcTypeEnum, nestedSelect, nestedResultMap, notNullColumn, columnPrefix, typeHandlerClass, flags, resultSet, foreignColumn, lazy);
  }

org.apache.ibatis.builder.MapperBuilderAssistant#buildResultMapping

public ResultMapping buildResultMapping(
      Class<?> resultType,
      String property,
      String column,
      Class<?> javaType,
      JdbcType jdbcType,
      String nestedSelect,
      String nestedResultMap,
      String notNullColumn,
      String columnPrefix,
      Class<? extends TypeHandler<?>> typeHandler,
      List<ResultFlag> flags,
      String resultSet,
      String foreignColumn,
      boolean lazy) {
    Class<?> javaTypeClass = resolveResultJavaType(resultType, property, javaType);
    TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);
    List<ResultMapping> composites = parseCompositeColumnName(column);
    return new ResultMapping.Builder(configuration, property, column, javaTypeClass)
        .jdbcType(jdbcType)
        .nestedQueryId(applyCurrentNamespace(nestedSelect, true))
        .nestedResultMapId(applyCurrentNamespace(nestedResultMap, true))
        .resultSet(resultSet)
        .typeHandler(typeHandlerInstance)
        .flags(flags == null ? new ArrayList<ResultFlag>() : flags)
        .composites(composites)
        .notNullColumns(parseMultipleColumnNames(notNullColumn))
        .columnPrefix(columnPrefix)
        .foreignColumn(foreignColumn)
        .lazy(lazy)
        .build();
  }

org.apache.ibatis.mapping.ResultMapping

   public ResultMapping build() {
      // lock down collections
      resultMapping.flags = Collections.unmodifiableList(resultMapping.flags);
      resultMapping.composites = Collections.unmodifiableList(resultMapping.composites);
      resolveTypeHandler();
      validate();
      return resultMapping;
    }
................................................................................

org.apache.ibatis.builder.MapperBuilderAssistant#addResultMap
//完成註冊

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

org.apache.ibatis.builder.xml.XMLMapperBuilder#buildStatementFromContext

解析select、insert、update、delete節點 
buildStatementFromContext(context.evalNodes("select|insert|update|delete"));

org.apache.ibatis.builder.xml.XMLMapperBuilder#buildStatementFromContext

  //解析select、insert、update、delete節點
  private void buildStatementFromContext(List<XNode> list) {
    if (configuration.getDatabaseId() != null) {
      buildStatementFromContext(list, configuration.getDatabaseId());
    }
    buildStatementFromContext(list, null);
  }

org.apache.ibatis.builder.xml.XMLMapperBuilder#buildStatementFromContext

  //處理所有的sql語句節點並註冊至configuration對象
  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);
      }
    }
  }

org.apache.ibatis.builder.xml.XMLStatementBuilder#parseStatementNode

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

基於xml分析
mappedStatement

  • id
  • sqlSource
  • paramterMap
  • resultMap
  • keyGenerator

mappedStatement數據結構分析

public final class MappedStatement {

  private String resource;//節點的完整的id屬性,包括命名空間
  private Configuration configuration;
  private String id;//節點的id屬性
  private Integer fetchSize;//節點的fetchSize屬性,查詢數據的條數
  private Integer timeout;//節點的timeout屬性,超時時間
  private StatementType statementType;//節點的statementType屬性,默認值:StatementType.PREPARED;疑問?
  private ResultSetType resultSetType;//節點的resultSetType屬性,jdbc知識
  private SqlSource sqlSource;//節點中sql語句信息
  private Cache cache;//對應的二級緩存
  private ParameterMap parameterMap;//已廢棄
  private List<ResultMap> resultMaps;//節點的resultMaps屬性
  private boolean flushCacheRequired;//節點的flushCache屬性是否刷新緩存
  private boolean useCache;//節點的useCache屬性是否使用二級緩存
  private boolean resultOrdered;
  private SqlCommandType sqlCommandType;//sql語句的類型,包括:INSERT, UPDATE, DELETE, SELECT
  private KeyGenerator keyGenerator;//節點keyGenerator屬性
  private String[] keyProperties;
  private String[] keyColumns;
  private boolean hasNestedResultMaps;//是否有嵌套resultMap
  private String databaseId;
  private Log statementLog;
  private LanguageDriver lang;
  private String[] resultSets;//多結果集使用

  MappedStatement() {
    // constructor disabled
  }
.............................................................
}

org.apache.ibatis.mapping.SqlSource

/**
 * Represents the content of a mapped statement read from an XML file or an annotation. 
 * It creates the SQL that will be passed to the database out of the input parameter received from the user.
 *
 * @author Clinton Begin
 */
public interface SqlSource {

  BoundSql getBoundSql(Object parameterObject);

}

包裝sql參數 入參

public class BoundSql {

  private final String sql;
  private final List<ParameterMapping> parameterMappings;
  private final Object parameterObject;
  private final Map<String, Object> additionalParameters;
  private final MetaObject metaParameters;
...........................
}

org.apache.ibatis.builder.xml.XMLMapperBuilder#buildStatementFromContext(java.util.List<org.apache.ibatis.parsing.XNode>, java.lang.String)

  //處理所有的sql語句節點並註冊至configuration對象
  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);
      }
    }
  }

org.apache.ibatis.builder.xml.XMLStatementBuilder#parseStatementNode

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

org.apache.ibatis.builder.MapperBuilderAssistant#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");
    }

    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;
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章