mybatis-初始化(一)mybatis-confg解析

概述

mybatis初始化主要包含mybatis全局配置加載、解析,mapper文件加載解析。本篇主要是對mybatis配置文件解析進行解讀。

先看下mybatis-config.xml有些啥內容

每節對應一個xml node。開幹!

解析入口

public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
  try {
    XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
    /*
     * 1. 執行xml解析
     * 2. 解析後的config,創建SqlSessionFactory
     */
    return build(parser.parse());
  } 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.
    }
  }
}

在SqlSessionFactoryBuilder.build()中,解析完Configuration直接創建SqlSessionFactory。

configuration解析

mybatis-config.xml的輸入流已經在XPathParser裏了。

public class XMLConfigBuilder extends BaseBuilder {

  /**
   * 是否已經解析
   */
  private boolean parsed;

  /**
   * Xpath解析器
   */
  private final XPathParser parser;

  /**
   * 當前應用的環境id
   */
  private String environment;
  
    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;
  }
}

xml配置構造器存儲XPath解析器,主要用它來完成xml相關的解析。

解析方法如下:

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

  //解析 configuration節點,configuration是根節點
  parseConfiguration(parser.evalNode("/configuration"));
  return configuration;
}
/**
 * 解析config.xml
 * @param root
 */
private void parseConfiguration(XNode root) {
  try {
    // 解析<properties/>
    propertiesElement(root.evalNode("properties"));

    // 解析<settings />
    Properties settings = settingsAsProperties(root.evalNode("settings"));
    // vfs實現類處理
    loadCustomVfs(settings);
    // 日誌實現類處理
    loadCustomLogImpl(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"));

    // Configuration屬性設置
    settingsElement(settings);

    // 解析<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);
  }
}

從上到下按照針對每個子xml node挨個解析,很清晰。

讓我們挨個看,重要的重點看,不重要的掃一眼。

properties解析

properties主要是爲了解決佔位符替換(${}),可以自定義變量,也可以外部引入。涉及到xml相關的知識不展開,主要是把解析好的properties存儲到parser和Configuration中,後續使用。

private void propertiesElement(XNode context) throws Exception {
  if (context != null) {
    //直接使用XNode提供的方法,將node解析成Properties
    Properties defaults = context.getChildrenAsProperties();

    // 引用外部properties解析支持
    String resource = context.getStringAttribute("resource");
    String url = context.getStringAttribute("url");
    if (resource != null && url != null) {
      throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
    }
    if (resource != null) {
      defaults.putAll(Resources.getResourceAsProperties(resource));
    } else if (url != null) {
      defaults.putAll(Resources.getUrlAsProperties(url));
    }
    Properties vars = configuration.getVariables();
    if (vars != null) {
      defaults.putAll(vars);
    }

    // 將解析好的 properties放到解析器中,進行後續動態值替換
    parser.setVariables(defaults);
    configuration.setVariables(defaults);
  }
}

settings解析

settings也當做properties處理。只看下解析邏輯,具體每個配置有什麼作用,可以去官網參考下。

<settings>
  <setting name="cacheEnabled" value="true"/>
  <setting name="lazyLoadingEnabled" value="true"/>
  <setting name="multipleResultSetsEnabled" value="true"/>
  <setting name="useColumnLabel" value="true"/>
  <setting name="useGeneratedKeys" value="false"/>
  <setting name="autoMappingBehavior" value="PARTIAL"/>
  <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
  <setting name="defaultExecutorType" value="SIMPLE"/>
  <setting name="defaultStatementTimeout" value="25"/>
  <setting name="defaultFetchSize" value="100"/>
  <setting name="safeRowBoundsEnabled" value="false"/>
  <setting name="mapUnderscoreToCamelCase" value="false"/>
  <setting name="localCacheScope" value="SESSION"/>
  <setting name="jdbcTypeForNull" value="OTHER"/>
  <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
private Properties settingsAsProperties(XNode context) {
  if (context == null) {
    return new Properties();
  }

  // 將settings轉換成properties
  Properties props = context.getChildrenAsProperties();
  // Check that all settings are known to the configuration class
  MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);

  // 遍歷通過setter方法判斷是否存在非法屬性
  for (Object key : props.keySet()) {
    if (!metaConfig.hasSetter(String.valueOf(key))) {
      throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
    }
  }
  return props;
}

TypeAlias解析

邏輯較簡單,具體別名處理在type中的alias已經講過了

private void typeAliasesElement(XNode parent) {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      // 大多數情況使用指定package的方式
      if ("package".equals(child.getName())) {
        String typeAliasPackage = child.getStringAttribute("name");
        // 通過typeAliasRegistry提供的批量註冊功能,註冊該包下的所有類
        configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
      } else {
        //單個的處理
        String alias = child.getStringAttribute("alias");
        String type = child.getStringAttribute("type");
        try {
          Class<?> clazz = Resources.classForName(type);
          if (alias == null) {
            typeAliasRegistry.registerAlias(clazz);
          } else {
            typeAliasRegistry.registerAlias(alias, clazz);
          }
        } catch (ClassNotFoundException e) {
          throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
        }
      }
    }
  }

plugins解析

這裏先了解下 插件是如何解析和註冊的。插件的具體內容將在mybatis整體介紹完之後再講解。

private void pluginElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      String interceptor = child.getStringAttribute("interceptor");
      Properties properties = child.getChildrenAsProperties();
      // 通過 別名 解析出類型,使用默認構造函數創建實例
      Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
      // 設置屬性值
      interceptorInstance.setProperties(properties);
      // 添加攔截器
      configuration.addInterceptor(interceptorInstance);
    }
  }
}

對象工廠

支持指定對象工廠,可以自定義對象創建過程,就是入參、出參。

private void objectFactoryElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    Properties properties = context.getChildrenAsProperties();
    // 別名 解析類型,創建實例
    ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
    // 設置屬性
    factory.setProperties(properties);
    // 添加Object工廠
    configuration.setObjectFactory(factory);
  }
}

對象包裝器工廠

用的少,略過

private void objectWrapperFactoryElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
    configuration.setObjectWrapperFactory(factory);
  }
}

反射器工廠

用的少,略過

private void reflectorFactoryElement(XNode context) throws Exception {
  if (context != null) {
    String type = context.getStringAttribute("type");
    ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
    configuration.setReflectorFactory(factory);
  }
}

默認配置

默認配置設置

private void settingsElement(Properties props) {
  configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
  configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
  configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
  configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
  configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
  configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
  configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
  configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
  configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
  configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
  configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
  configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
  configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
  configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
  configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
  configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
  configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
  configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
  configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
  configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
  configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
  configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
  configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
  configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
  configuration.setLogPrefix(props.getProperty("logPrefix"));
  configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
}

環境信息解析

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <dataSource type="POOLED">
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
    </dataSource>
  </environment>
</environments>

多環境一般不使用mybatis的多environment配置,所以 用的少。

private void environmentsElement(XNode context) throws Exception {
  if (context != null) {
    // 如果未指定,則解析標籤上的默認
    if (environment == null) {
      environment = context.getStringAttribute("default");
    }
    for (XNode child : context.getChildren()) {
      String id = child.getStringAttribute("id");

      // 如果是當前應用的環境纔會進行設置和添加
      if (isSpecifiedEnvironment(id)) {

        // 解析<transactionManager />標籤
        TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
        // 解析<dataSource />標籤
        DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
        DataSource dataSource = dsFactory.getDataSource();
        Environment.Builder environmentBuilder = new Environment.Builder(id)
            .transactionFactory(txFactory)
            .dataSource(dataSource);
        configuration.setEnvironment(environmentBuilder.build());
      }
    }
  }
}

數據庫廠商id解析

用的少,略過

private void databaseIdProviderElement(XNode context) throws Exception {
  DatabaseIdProvider databaseIdProvider = null;
  if (context != null) {
    String type = context.getStringAttribute("type");
    // awful patch to keep backward compatibility
    if ("VENDOR".equals(type)) {
      type = "DB_VENDOR";
    }
    Properties properties = context.getChildrenAsProperties();
    databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();
    databaseIdProvider.setProperties(properties);
  }
  Environment environment = configuration.getEnvironment();
  if (environment != null && databaseIdProvider != null) {
    String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
    configuration.setDatabaseId(databaseId);
  }
}

類型處理器解析

即可指定包名批量註冊,又可以單個註冊。

private void typeHandlerElement(XNode parent) {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      if ("package".equals(child.getName())) {
        String typeHandlerPackage = child.getStringAttribute("name");
        // 通過包名批量註冊typeHandler
        typeHandlerRegistry.register(typeHandlerPackage);
      } else {
        String javaTypeName = child.getStringAttribute("javaType");
        String jdbcTypeName = child.getStringAttribute("jdbcType");
        String handlerTypeName = child.getStringAttribute("handler");
        Class<?> javaTypeClass = resolveClass(javaTypeName);
        JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
        Class<?> typeHandlerClass = resolveClass(handlerTypeName);
        if (javaTypeClass != null) {
          if (jdbcType == null) {
            typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
          } else {
            typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
          }
        } else {
          typeHandlerRegistry.register(typeHandlerClass);
        }
      }
    }
  }
}

mapper映射文件解析

重點,mapper映射文件就是我們寫sql的文件。解析映射文件,然後和Mapper接口建立映射。

看下mapper的配置內容實例:

<!-- 使用相對於類路徑的資源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定資源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口實現類的完全限定類名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- 將包內的映射器接口實現全部註冊爲映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

共有4中方式配置mapper.xml,看下代碼如何解析

private void mapperElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      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) {
          // 通過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) {
          // 通過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接口的相同路徑嘗試加載
          Class<?> mapperInterface = Resources.classForName(mapperClass);
          configuration.addMapper(mapperInterface);
        } else {
          throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
        }
      }
    }
  }
}

這裏分兩種情況,

一:配置的是Mapper Class,包名和class,是先去加載mapper接口,然後再當前路徑將.java替換成.xml嘗試加載。

二:直接配置的Mapper.xml,那麼委託給XMLMapperBuilder進行具體內容解析。

Mapper.xml的內容具體比較複雜,單獨放在一篇文章進行解析。

總結

mybatis-config的解析比較簡單,只要可以對着官網的文檔,先看配置的內容和格式,再看代碼如何解析,按部就班看幾眼就能懂。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章