欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mybatis 文档篇 2.8:Configuration 之 DatabaseIdProvider

程序员文章站 2022-04-22 07:59:42
...

1 Configuration Structure

2 DatabaseIdProvider

2.1 默认的 DatabaseIdProvider

MyBatis is able to execute different statements depending on your database vendor.
作用:MyBatis 可以根据不同的数据库厂商执行不同的语句。

The multi-db vendor support is based on the mapped statements databaseId attribute. MyBatis will load all statements with no databaseId attribute or with a databaseId that matches the current one.In case the same statement is found with and without the databaseId the latter will be discarded.
这种多数据厂商的支持是基于映射语句的 databaseId 属性。MyBatis 会加载不带 databaseId 属性或者带有当前数据库的 databaseId 的所有语句。如果同时找到带 databaseId 和不带 databaseId 的语句,后者会被舍弃。

To enable the multi vendor support add a databaseIdProvider to mybatis-config.xml file as follows:
可以在 mybatis-config.xml 中添加 databaseIdProvider 以打开对多数据厂商的支持:

<databaseIdProvider type="DB_VENDOR" />

The DB_VENDOR implementation databaseIdProvider sets as databaseId the String returned by DatabaseMetaData#getDatabaseProductName().
DB_VENDOR 对于 databaseIdProvider 的实现会通过 DatabaseMetaData#getDatabaseProductName() 返回的字符串来设置 databaseId。

Given that usually that string is too long and that different versions of the same product may return different values, you may want to convert it to a shorter one by adding properties like follows:
由于通常情况下这个字符串会很长并且同一个产品的的不同版本会返回不同的值,你可能会想要像下面这样通过添加一些属性的方式让它变短:

<databaseIdProvider type="DB_VENDOR">
  <property name="SQL Server" value="sqlserver"/>
  <property name="DB2" value="db2"/>
  <property name="Oracle" value="oracle" />
</databaseIdProvider>

When properties are provided, the DB_VENDOR databaseIdProvider will search the property value corresponding to the first key found in the returned database product name or "null" if there is not a matching property.In this case, if getDatabaseProductName() returns "Oracle (DataDirect)" the databaseId will be set to "oracle".
当提供这些属性时, DB_VENDOR databaseIdProvider 将会查找对应于返回的数据库产品名称的第一个键的属性值,如果没有匹配的属性值将会被设置为 null。在这个例子中,如果 getDatabaseProductName() 返回的是“Oracle (DataDirect)”,databaseId 将会被设置为 “oracle”。

2.2 自定义 DatabaseIdProvider

You can build your own DatabaseIdProvider by implementing the interface org.apache.ibatis.mapping.DatabaseIdProvider and registering it in mybatis-config.xml:
你可以通过实现接口 org.apache.ibatis.mapping.DatabaseIdProvider 并在 mybatis-config.xml 中注册的方式创建你自己的 DatabaseIdProvider。

public interface MyDatabaseIdProvider {
  void setProperties(Properties p);
  String getDatabaseId(DataSource dataSource) throws SQLException;
}

具体如下:
1.实现 DatabaseIdProvider 接口:

public class MyDatabaseIdProvider implements DatabaseIdProvider {
    Logger logger = Logger.getLogger(MyDatabaseIdProvider.class);
    private Properties properties;

    @Override
    public void setProperties(Properties p) {
        this.properties = p;
    }

    @Override
    public String getDatabaseId(DataSource dataSource) throws SQLException {
        Connection connection = dataSource.getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        String databaseProductName = metaData.getDatabaseProductName();
        logger.info("MyDatabaseIdProvider-Current DataBase Product Name is: " + databaseProductName);
        for (Object key : properties.keySet()) {
            if (key.equals(databaseProductName)) {
                logger.info("MyDatabaseIdProvider-Find a matched property value: " + properties.get(key));
                return (String) properties.get(key);
            }
        }
        return null;
    }
}

2.mybatis-config.xml 中配置多个 environment,并指定自定义 databaseIdProvider :

<environments default="developmentOracle">
  <environment id="development">
      <transactionManager type="JDBC"/>
         <dataSource type="POOLED">
            <property name="driver" value="${jdbc.driver}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
         </dataSource>
  </environment>
  <environment id="developmentOracle">
     <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${oracle.driver}"/>
            <property name="url" value="${oracle.url}"/>
            <property name="username" value="${oracle.username}"/>
            <property name="password" value="${oracle.password}"/>
      </dataSource>
    </environment>
</environments>
 
<!--自定义 databaseIdProvider-->
<databaseIdProvider type="com.zhaoxueer.learn.my.MyDatabaseIdProvider">
  <property name="Oracle" value="oracle"/>
  <property name="MySQL" value="mysql"/>
</databaseIdProvider>

3.Mapper.xml 中的语句要指定 databaseId:

 <select id="selectByPhone" resultType="Author" databaseId="mysql">
    select
          id, name, sex, phone
    from author
    where phone = #{phone}
 </select>

 <select id="selectByPhone" resultType="Author" databaseId="oracle">
    select
          id, name, sex
    from author
    where phone = #{phone}
 </select>

通过上面的配置和代码编写,MyBatis 会执行 databaseId="oracle" 的语句。

最后

说明:MyBatis 官网提供了简体中文的翻译,但个人觉得较为生硬,甚至有些地方逻辑不通,于是自己一个个重新敲着翻译的(都不知道哪里来的自信...),有些地方同官网翻译有出入,有些倔强地保留了自己的,有的实在别扭则保留了官网的,这些都会在实践中一一更正。鉴于个人英文能力有限,文章中保留了官方文档原英文介绍(个别地方加以调整修剪),希望有缘看到这里的朋友们能够有自己的理解,不会被我可能错误或不合理的翻译带跑偏(〃'▽'〃),欢迎指正!

当前版本:mybatis-3.5.0
官网文档:MyBatis
官网翻译:MyBatis 简体中文
项目实践:MyBatis Learn