如何在spring中配置使得mybatis3.1.1中支持vendor方式的multi-db(多数据库)

来源:互联网 发布:jsp页面显示数据库表 编辑:程序博客网 时间:2024/06/05 00:38
转自:http://herry.iteye.com/blog/148问题解决:
而在mybatis3.1.0之后就内在的支持multi-db了,可以在select/update/delete/insert加上databaseId的方式来标识不同的数据库,也可以直接使用属性<if test="_databaseId == 'MySQL'">来判断不同的数据库。那如何在spring中集成mybatis使其支持multi-db的特性呢?在mybatis的官方文档中并没有具体说明,后来通过查看源码而得到的配置。
下面的vendorProperties中key的值是通过数据库产品的名称来的:
Java代码 收藏代码
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中的配置项如下:
Java代码 收藏代码
<?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> 8271
阅读全文
0 0
原创粉丝点击