Mybatis 的脉络梳理01之解析mybatis-config.xml

Mybatis 最主要的就是 mybatis-config.xml 和 Mapper.xml 这两个 XML 文件。mybatis-config.xml 用于 mybatis 环境的配置,Mapper.xml 用于实体类与数据库之间的交互,使用户避免大量的 jdbc 代码。

1. Mybatis 如何解析 mybatis-config.xml 文件

  • 既然要知道如何解析,那么就从使用开始。最简单的使用如下:
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  • 可以看到,读取文件作为字节流,传入 SqlSessionFactoryBuilder 构建工厂创建一个指定配置的 sqlSessionFactory(当然,配置也可以在返回的sqlSessionFactory 对象进行更换)。

1.1 先来看 SqlSessionFactoryBuilder

  • 没有指定构造函数,即只能使用默认的空构造。
  • 具有 9 个 build 方法。不过细看,主要最终使用的有三个方法
    • SqlSessionFactory build(Reader reader, String environment, Properties properties):使用(字符流的 xml 配置文件,指定的环境environment,属性配置文件properties)构造工厂。
    • SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) :使用(字节流的 xml 配置文件,指定的环境environment,属性配置文件properties)构造工厂。
    • SqlSessionFactory build(Configuration config):不论使用字节流还是字符流,最终得到一个配置类 config,并将其应用于生成的 SqlSessionFactory。
/* 参数解析:
 * reader/inputStream: 字节流/字符流的 xml文件
 * environment:mybatis 使用的环境,该属性对应于 xml 文件 environments 属性的 default 属性
 * properties:属性配置文件,与 xml 文件 properties 属性对应,相同的属性会覆盖
 * config:对应于 xml 文件的 configuration */
public class SqlSessionFactoryBuilder {
  public SqlSessionFactory build(Reader reader) {
    return build(reader, null, null);
  }
  public SqlSessionFactory build(Reader reader, String environment) {
    return build(reader, environment, null);
  }
  public SqlSessionFactory build(Reader reader, Properties properties) {
    return build(reader, null, properties);
  }
  public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
      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.
      }
    }
  }
  public SqlSessionFactory build(InputStream inputStream) {
    return build(inputStream, null, null);
  }
  public SqlSessionFactory build(InputStream inputStream, String environment) {
    return build(inputStream, environment, null);
  }
  public SqlSessionFactory build(InputStream inputStream, Properties properties) {
    return build(inputStream, null, properties);
  }
  public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
    try {
      XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
      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.
      }
    }
  }
  public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
  }
}

1.1.1 以字节流的 build 为例,来看xml文件的解析

  • 从代码中可以看到,先创建了一个 XMLConfigBuilder类型的 parser 对象,再将 parser 进行解析得到一个 Configuration 对象,使用 Configuration 进行配置,得到一个 SqlSessionFactory 实例并返回。
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
  try {
    /* new 一个 Builder 类,主要用于解析 xml 文件 */
    XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
    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.
    }
  }
}

1.1.2 parser.parse() 解析过程

public Configuration parse() {
	/* 判断是否该 xml 文件已解析 */
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true; // 设置该文件已经解析
    /* parser.evalNode("/configuration") 返回已解析 configuration 的 XNode 节点
     * parseConfiguration(Xnode node) 解析 configuration 的子节点 */
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
}

1.1.3 configuration 子节点的解析

首先来看 XNode 类的几个属性

/* node:被封装的Node对象,包含对应的节点信息
 * name: 节点名称,如 configuration
 * body: 节点的 body 内容(文本内容,子标签不属于body)
 * attributes: 属性集合,如 <property name="username" value="root"/> 的username=root
 * variables: 属性集合,该属性用于配置文件中<properties>节点下引入的或定义的键值对
 * xpathParser: 解析器,底层使用使用 java dom 解析 xml 文件
 * name: 节点名称,如 configuration
 * name: 节点名称,如 configuration
 * */
private final Node node; 
private final String name;
private final String body;
private final Properties attributes;
private final Properties variables;
private final XPathParser xpathParser;
  • 解析 configuration 标签 的子标签,即常用的配置properties、settings等
/* 依次解析configuration 的所有子标签
 * xml 标签必须按顺序是 dtd 文件的规范,而不是这里解析顺序的原因
 * 注意:root.evalNode("XXX") 方法为解析 XXX 节点,并包装为 XNode 节点返回
 */
private void parseConfiguration(XNode root) {
    try {
      //issue #117 read properties first
      propertiesElement(root.evalNode("properties"));
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      typeAliasesElement(root.evalNode("typeAliases"));
      pluginElement(root.evalNode("plugins"));
      objectFactoryElement(root.evalNode("objectFactory"));
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      environmentsElement(root.evalNode("environments"));
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      typeHandlerElement(root.evalNode("typeHandlers"));
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
}

注意,任意子节点可不进行配置

1.1.3.1 properties
  • xml 配置的完整的 properties 节点示例如下:
<!-- 
 url: 一般用于引入 网络资源 or 本地系统文件
 resource: 一般引入项目内 resources 目录下的文件
 注意:url 与 resource 不能共用,代码中可得到体现
  -->
<properties url="file:///G:\db.properties">
    <property name="username" value="root" />
    <property name="password" value="123456" />
</properties>
<properties resource="db.properties">
    <property name="username" value="root" />
    <property name="password" value="123456" />
</properties>
  • 解析 properties 节点
/* 若context为空,则代表 xml 文件没有配置 properties,无需处理 
 * 若不为空,按照以下步骤执行
 *   1. context.getChildrenAsProperties():获取所有 property 节点的键值对
 *   2. 获取 resource、url 属性配置的文件路径,
 * 		若 resource 与 url 都不为 null 则代表都配置了,报错BuilderException
 *   3. 获取不为null的配置文件的所有键值对,并且添加进 defaults
 *   4. getVariables():build() 方法传入的 properties 键值对,不为 null 添加进 defaults
 *   5. parser.setVariables(defaults):parser解析器设置变量键值对
 *   6. configuration.setVariables(defaults): configuration配置类设置变量键值对
 * */
private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      Properties defaults = context.getChildrenAsProperties();
      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);
      }
      parser.setVariables(defaults);
      configuration.setVariables(defaults);
    }
}
1.1.3.2 settings
  • xml 配置的完整的 settings 节点示例如下:
<settings>
    <setting name="cacheEnabled" value="true" />
</settings>
  • 解析 settings 节点
/**
 * 若 context 为 null 则 xml 没有配置 settings,返回空的键值对 
 * 若 context 不为 null
 * 	1. getChildrenAsProperties():获取全部 setting 配置的键值对
 *  2. metaConfig:  通过反射获取 Configuration 的所有元信息,包括属性、方法等
 *  3. 循环判断 props 的 key 是否在 Configuration 拥有对应的 setter 方法,
 * 		即判断 Configuration 是否开放某属性的修改权限
 *  4. 验证完毕后返回 props
 * */
private Properties settingsAsProperties(XNode context) {
    if (context == null) {
      return new Properties();
    }
    Properties props = context.getChildrenAsProperties();
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
    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;
}
  • loadCustomVfs(Properties props):加载自定义的 VFS(虚拟文件系统),默认为 未设置
private void loadCustomVfs(Properties props) throws ClassNotFoundException {
    String value = props.getProperty("vfsImpl");
    if (value != null) {
      String[] clazzes = value.split(",");
      for (String clazz : clazzes) {
        if (!clazz.isEmpty()) {
          @SuppressWarnings("unchecked")
          Class<? extends VFS> vfsImpl = (Class<? extends VFS>)Resources.classForName(clazz);
          configuration.setVfsImpl(vfsImpl);
        }
      }
    }
}
  • loadCustomLogImpl(Properties props):指定 MyBatis 所用日志的具体实现,默认为 未设置
private void loadCustomLogImpl(Properties props) {
    Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
}
1.1.3.3 typeAliases
  • xml 配置的完整的 typeAliases 节点示例如下:
<typeAliases>
    <typeAlias type="com.jack.pojo.User" alias="User" />
    <package name="com.jack.pojo" />
</typeAliases>
  • 解析 typeAliases 节点
 /**
 * 若 parent 为 null 则 xml 没有配置 typeAliases,无需处理 
 * 若 context 不为 null
 * 	  1. getChildren():获取全部 typeAliases 配置的节点信息
 *    2. 若子节点为 package:
 * 		  2.1 getStringAttribute("name"): 获取包名
 * 		  2.2 getTypeAliasRegistry(): 获取类型别名注册器
 * 		  2.3 registerAliases(typeAliasPackage): 注册包下的所有class,后面详解
 *    3. 若子节点为 typeAlias:
 * 		  3.1 分别获取 别名alias, 配置别名的类 type
 * 		  3.2 registerAlias(alias, clazz):注册别名的方法,后面详解
 * */
private void typeAliasesElement(XNode parent) {

  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      if ("package".equals(child.getName())) {
        String typeAliasPackage = child.getStringAttribute("name");
        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);
        }
      }
    }
  }
}
1.1.3.4 plugin
  • xml 配置的完整的 plugin 节点示例如下:
  • 自定义方法拦截类,实现 Interceptor 接口
public interface Interceptor {
  Object intercept(Invocation invocation) throws Throwable;
  default Object plugin(Object target) {
    return Plugin.wrap(target, this);
  }
  default void setProperties(Properties properties) {}
}
@Intercepts({@Signature(
  type= Executor.class,
  method = "update",
  args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
  private Properties properties = new Properties();
  public Object intercept(Invocation invocation) throws Throwable {
    // implement pre processing if need
    Object returnObject = invocation.proceed();
    // implement post processing if need
    return returnObject;
  }
  public void setProperties(Properties properties) {
    this.properties = properties;
  }
}
  • 将自定义的插件类在 xml 中配置
<plugins>
  <plugin interceptor="ExamplePlugin">
    <property name="someProperty" value="100"/>
  </plugin>
</plugins>
  • 解析 plugin 节点
/* 老规矩,parent 为null,无配置,不操作
 * parent 不为null:
 * 	  1. getChildren():获取所有配置的插件(plugin可以有多个)
 *    2. getChildrenAsProperties(): 获取配置的属性节点(property)
 *    3. 生成一个 Interceptor 的实例对象
 * 		3.1. resolveClass(interceptor): 首先从别名配置中查找类,找不到则使用classForName() 加载
 * 		3.2 newInstance(): 利用 class 对象生成一个实例,使用的是空构造方法
 *    4. setProperties(): 为实例对象设置属性
 *    5. addInterceptor(): 将对象添加进 configuration (底层采用 ArrayList 存储多个插件对象)
 *  */
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).newInstance();
        interceptorInstance.setProperties(properties);
        configuration.addInterceptor(interceptorInstance);
      }
    }
}
1.1.3.5 objectFactory
  • xml 配置的完整的 objectFactory 节点示例如下:
  • 自定义对象工厂类,继承 DefaultObjectFactory
public class ExampleObjectFactory extends DefaultObjectFactory {
    @Override
    public Object create(Class type) {
        return super.create(type);
    }
    public void setProperties(Properties properties) {
        super.setProperties(properties);
    }
    @Override
    public <T> boolean isCollection(Class<T> type) {
        return Collection.class.isAssignableFrom(type);
    }
}
  • 将自定义的工厂类在 xml 中配置
<objectFactory type="ExampleObjectFactory">
  <property name="someProperty" value="100"/>
</objectFactory>
  • 解析 objectFactory 节点
/* 与 plugin 类似,获取配置的对象工厂类,生成实例factory,设置属性值,添加进configuration */
private void objectFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties properties = context.getChildrenAsProperties();
      ObjectFactory factory = (ObjectFactory) resolveClass(type).newInstance();
      factory.setProperties(properties);
      configuration.setObjectFactory(factory);
    }
}
1.1.3.6 objectWrapperFactory
  • xml 配置的完整的 typeAliases 节点示例如下:
  • 自定义对象包装工厂,即对 object 进行一定的处理包装
public class ExampleObjectWrapperFactory implements org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory
{
    public boolean hasWrapperFor(Object object) {
        return false;
    }
    public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
        return null;
    }
}
  • 将自定义的工厂类在 xml 中配置
<objectWrapperFactory type="ExampleObjectWrapperFactory" />
  • 解析 objectWrapperFactory 节点
/* 与 plugin 类似,获取配置的对象包装工厂类,生成实例factory,添加进configuration */
private void objectWrapperFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).newInstance();
      configuration.setObjectWrapperFactory(factory);
    }
}
1.1.3.7 reflectorFactory
  • xml 配置的完整的 reflectorFactory 节点示例如下:
  • 自定义反射工厂类,实现 ReflectorFactory
public class ExampleReflectorFactory implements ReflectorFactory {
    public boolean isClassCacheEnabled() {
        return false;
    }
    public void setClassCacheEnabled(boolean classCacheEnabled) {}
    public Reflector findForClass(Class<?> type) {
        return null;
    }
}
  • 将自定义的反射工厂类在 xml 中配置
<reflectorFactory type="ExampleReflectorFactory" />
  • 解析 reflectorFactory 节点
/* 与 plugin 类似,获取配置的反射工厂类,生成实例factory,添加进configuration */
private void reflectorFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ReflectorFactory factory = (ReflectorFactory) resolveClass(type).newInstance();
      configuration.setReflectorFactory(factory);
    }
}

横插一脚,settingsElement(settings); 设置一系列的属性。

/* 一堆属性,用到再来看吧 */
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")));
}
1.1.3.8 environments
  • xml 配置的完整的 environments 节点示例如下:
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC">
            <property name="test" value="test"/>
        </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>
  • 解析 environments 节点
/* 老规矩,context 为null,无配置,不操作
 * context 不为null:
 * 	  1. environment: build方法传入,没有传入即为null,使用 default 属性配置,
 * 		可看出build方法的优先级比 default属性配置高
 *    2. getChildren(): 获取多套环境的配置
 *    3. getStringAttribute("id"):获取当前环境的id,isSpecifiedEnvironment(id):判断是否为当前指定的环境id
 *    4. transactionManagerElement(): 解析transactionManager节点,生成事务管理工厂
 *    5. dataSourceElement(): 解析dataSource节点,生成数据源工厂
 *    6. getDataSource(): 获取数据库信息
 *    7. 生成 Environment.Builder 类(环境创建类),构建环境后添加进configuration
 *  */
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)) {
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          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());
        }
      }
    }
}
1.1.3.9 databaseIdProvider
  • xml 配置的完整的 databaseIdProvider 节点示例如下:
  • 也可生成自定义的 ExampleDatabaseIdProvider,实现 DatabaseIdProvider 即可
<databaseIdProvider type="DB_VENDOR">
  <property name="SQL Server" value="sqlserver"/>
  <property name="DB2" value="db2"/>
  <property name="Oracle" value="oracle" />
</databaseIdProvider>
  • 解析 databaseIdProvider 节点
/* 老规矩,context 为null,无需操作,因为 databaseIdProvider 必定为 null
 * context 不为null:
 * 	  1. 获取type类型,若为 VENDOR,设置为 DB_VENDOR(为了兼容前面的版本)
 *    2. getChildrenAsProperties(): 获取所有的 property 属性配置
 *    3. 根据 type 生成一个 databaseIdProvider 实例并设置 xml 配置的属性值
 * 获取环境
 *    4. 若 environment、databaseIdProvider 都不为 null,获取 databaseId 并设置进 configuration
 * *  */
private void databaseIdProviderElement(XNode context) throws Exception {
    DatabaseIdProvider databaseIdProvider = null;
    if (context != null) {
      String type = context.getStringAttribute("type");
      if ("VENDOR".equals(type)) {
        type = "DB_VENDOR";
      }
      Properties properties = context.getChildrenAsProperties();
      databaseIdProvider = (DatabaseIdProvider) resolveClass(type).newInstance();
      databaseIdProvider.setProperties(properties);
    }
    Environment environment = configuration.getEnvironment();
    if (environment != null && databaseIdProvider != null) {
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
      configuration.setDatabaseId(databaseId);
    }
}
1.1.3.10 typeHandler
  • xml 配置的完整的 typeHandler 节点示例如下:
  • 自定义一个处理器,继承 BaseTypeHandler
public class ExampleTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {

    }
    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return null;
    }
    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return null;
    }
    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
  • 将自定义的类型处理器在 xml 中配置
<typeHandlers>
    <typeHandler handler="ExampleTypeHandler"  javaType="java.lang.String" jdbcType="VARCHAR"></typeHandler>
    <package name="com.jack.typeHandler" />
</typeHandlers>
  • 解析 typeHandler 节点
/* 老规矩,parent 为null,无需操作
 * parent 不为null:
 * 	  1. 获取所有的属性节点,包括typeHandler 和 package
 *    2. 若属性为 typeHandler,获取 javaType、jdbcType、handler,
 * 		得到其对应的类型,并添加进 typeHandlerRegistry(注意,dtd文件设置handler属性必填)
 *    3. 若属性为 package,将指定包下的类型处理器注册进 typeHandlerRegistry
 * *  */
private void typeHandlerElement(XNode parent) {
  if (parent != null) {
    for (XNode child : parent.getChildren()) 
      if ("package".equals(child.getName())) {
        String typeHandlerPackage = child.getStringAttribute("name");
        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);
        }
      }
    }
  }
}
1.1.3.10 mapper
  • xml 配置的完整的 mapper 节点示例如下:
  • 官方例子,resource、url、class 不能同时配置,后面代码可证明
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
</mappers>
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
</mappers>
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
</mappers>
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>
  • 解析 mapper 节点
/* 老规矩,parent 为null,无需操作
 * parent 不为null:
 * 	  1. 获取所有的属性节点,包括 resource、url、class 和 package
 *    2. 若属性为 package,将指定包下的 mapper 文件添加进 configuration
 *    3. 若属性不为 package,获取resource、url、class的属性值(没有配置为 null)
 * 		3.1 若为 resource 不为null,url、class 为 null,读取 resource 文件,生成 XMLMapperBuilder类,解析 mapper
 * 		3.2 若为 url 不为null,resource 、class 为 null,读取 url 文件,生成 XMLMapperBuilder类,解析 mapper
 * 		3.3 若为 class 不为null,resource 、url 为 null,获取 class 类型,添加进 configuration
 * 		3.4 其他情况,即配置了两种或以上,报错 BuilderException
 * *  */
private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        /* 处理指定包的 mapper.xml 文件 */
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          configuration.addMappers(mapperPackage);
        } else {
          /* resource:一般用于项目内的文件
           * url: 一般用于网络资源或本地系统的文件
           * class: 直接把类接口传入
           *  */
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          if (resource != null && url == null && mapperClass == null) {
            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) {
            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) {
            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.");
          }
        }
      }
    }
}

总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值