spring中xml文件中的配置:java
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass"><value>oracle.jdbc.driver.OracleDriver</value></property> <property name="jdbcUrl"><value>jdbc:oracle:thin:@127.0.0.1:1521:ORACLE</value></property> <property name="user"><value>htctposp</value></property> <property name="password"><value>htctposp</value></property> <property name="minPoolSize"><value>1</value></property> <property name="maxPoolSize"><value>5</value></property> <property name="maxIdleTime"><value>1800</value></property> </bean> <bean id="dataSource2" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/mysql?characterEncoding=UTF8"></property> <property name="username" value="root"></property> <property name="password" value="1111"></property> </bean> <bean id="dataSource" class="com.huateng.util.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="dataSource1" value-ref="dataSource1"/> <entry key="dataSource2" value-ref="dataSource2"/> </map> </property> <property name="defaultTargetDataSource" ref="dataSource1"/> </bean> <!-- SqlMap setup for iBATIS Database Layer --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:com/xxx/xxx/dao/sqlmap/sql-map-config.xml"/> </bean>
寫兩個工具類DbContextHolder和DynamicDataSource,以下:mysql
public class DynamicDataSource extends AbstractRoutingDataSource{ static Logger log=Logger.getLogger("DynamicDataSource"); /* (non-Javadoc) * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey() */ protected Object determineCurrentLookupKey() { return DbContextHolder.getDbType(); } }
public class DbContextHolder { private static final ThreadLocal contextHolder = new ThreadLocal(); public static void setDbType(String dbType){ contextHolder.set(dbType); } public static String getDbType(){ return (String)contextHolder.get(); } public static void clearDbType(){ contextHolder.remove(); } }
通常在調用service層以前就要切換數據庫(通常要在action中或者說在事務外圍更準確),切換數據庫的代碼:
spring
DbContextHolder.setDbType("dataSource2");
參考:sql
https://blog.csdn.net/f_d_q/article/details/6927546 數據庫
http://exceptioneye.iteye.com/blog/1698090oracle