Spring MyBatis Oracle 多数据源
数据源1
<bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@//IP地址1:1521/数据库名1" /> <property name="username" value="用户名" /> <property name="password" value="密码" /> </bean> <bean id="sqlSessionFactory1" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource1" /> <property name="configLocation" value="classpath:myBatis/myBatis-Configuration1.xml" /> </bean> <bean id="mapper1" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zxg.dao1" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory1" /> </bean> <bean id="transactionManager1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource1" /> </bean> <tx:annotation-driven transaction-manager="transactionManager1" />
数据源2
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@//IP地址2:1521/数据库名2" /> <property name="username" value="用户名" /> <property name="password" value="密码" /> </bean> <bean id="sqlSessionFactory2" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource2" /> <property name="configLocation" value="classpath:myBatis/myBatis-Configuration2.xml" /> </bean> <bean id="mapper2" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zxg.dao2" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory2" /> </bean> <bean id="transactionManager2" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource2" /> </bean> <tx:annotation-driven transaction-manager="transactionManager2" />
注:xx1Mapper.java 和 xx1Mapper.xml 、 xx2Mapper.java 和 xx2Mapper.xml
上下文中不能出现同名的
结果:操作db1 调用 mapper1 ,操作db2 调用 mapper2
配置多数据源时需注意的单元测试问题:
@ContextConfiguration(locations = { "classpath*:spring/root/private_*.xml" }) @RunWith(SpringJUnit4ClassRunner.class) @Transactional
如果 @Transactional 不指定具体的,会报异常
java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional test for test context
需要具体指定一个 TransactionManager
例如:
@Transactional("txManagerAlpha")