在mybatis3.1.0之后就内在的支持multi-db了,可以在select/update/delete/insert加上databaseId的方式来标识不同的数据库,也可以直接使用属性<if test="_databaseId == 'MySQL'">来判断不同的数据库。那如何在spring中集成mybatis使其支持multi-db的特性呢?在mybatis的官方文档中并没有具体说明,后来通过查看源码而得到的配置。下面的vendorProperties中key的值是通过数据库产品的名称来的:

private String getDatabaseProductName(DataSource dataSource) throws SQLException { 
   Connection con = null; 
   try { 
      con = dataSource.getConnection(); 
      DatabaseMetaData metaData = con.getMetaData(); 
      return metaData.getDatabaseProductName(); 
   } finally { 
   if (con != null) { 
     try { 
       con.close(); 
     } catch (SQLException e) { 
       // ignored 
     } 
    } 
  } 
} 

主要的spring中的配置项如下:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
<property name="locations" value="classpath:datasource.properties"/> 
</bean> 

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
<property name="driverClassName" value="${jdbc.driverClassName}" /> 
<property name="url" value="${jdbc.url}" /> 
<property name="username" value="${jdbc.usename}" /> 
<property name="password" value="${jdbc.password}" /> 
</bean> 

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
<property name="dataSource" ref="dataSource" /> 
</bean> 

<bean id="vendorProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 
<property name="properties"> 
<props> 
<prop key="SQL Server">sqlserver</prop> 
<prop key="DB2">db2</prop> 
<prop key="Oracle">oracle</prop> 
<prop key="MySQL">mysql</prop> 
</props> 
</property> 
</bean> 

<bean id="databaseIdProvider" class="org.apache.ibatis.mapping.VendorDatabaseIdProvider"> 
<property name="properties" ref="vendorProperties"/> 
</bean> 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 
<property name="mapperLocations" value="classpath*:DYCloudTaskMapper.xml" /> 
<property name="dataSource" ref="dataSource" /> 
<property name="databaseIdProvider" ref="databaseIdProvider"/> 
</bean> 


<bean id="DYCloudTaskMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
<property name="mapperInterface" value="DYCloudTaskMapper" /> 
<property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
</bean> 

</beans>

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐