spring中xml文件中的配置:
<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,如下:
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中或者说在事务外围更准确),切换数据库的代码:
DbContextHolder.setDbType("dataSource2");
参考:
https://blog.csdn.net/f_d_q/article/details/6927546
http://exceptioneye.iteye.com/blog/1698090