SSM框架下的多数据源配置------以MySql数据库和PostgreSql数据库为例
一、引入MySql数据库驱动包和PostgreSql数据库驱动包,引入Druid数据库连接池jar包,在构建Spring时不要忘了加入spring-jdbc依赖包。
二、自定义动态数据库切换类:
package com.xxx.xxx.common.dynamicdatasource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态切换数据源
*
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
/** mysql数据库标识 */
public static final String mysqlDataSource = "mysqlDataSource";
/** oracle数据库标识 */
public static final String oracleDataSource = "oracleDataSource";
/** postgresql数据库标识 */
public static final String postgresqlDataSource = "postgresqlDataSource";
/** sqlserver数据库标识 */
public static final String sqlserverDataSource = "sqlserverDataSource";
/** 当前线程的上下文 */
public static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
/**
* 设置数据源类型
*
* @param customerBDType 用户数据类型
*/
public static void setCustomerDBType(String customerBDType) {
contextHolder.set(customerBDType);
}
/**
* 获取数据源类型
*
* @return
*/
public static String getCustomerDBType() {
return contextHolder.get();
}
/**
* 移除数据源类型
*/
public static void clearCustomerDBType() {
contextHolder.remove();
}
@Override
protected Object determineCurrentLookupKey() {
return getCustomerDBType();
}
}
三、在spring-mybatis.xml中配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLS