日期:2014-05-16 浏览次数:20655 次
问题起源:
同一个项目适应多种数据库,基本上是企业应用的常见需求。以往在mybatis中的支持是通过扩展dao而来实现的,参考:
http://code.google.com/p/mybatis/issues/detail?id=21.
问题解决:
而在mybatis3.1.0之后就内在的支持multi-db了,可以在select/update/delete/insert加上databaseId的方式来标识不同的数据库,也可以直接使用属性<if test="_databaseId == 'MySQL'">来判断不同的数据库。那如何在spring中集成mybatis使其支持multi-db的特性呢?在mybatis的官方文档中并没有具体说明,后来通过查看源码,得到主要的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>