spring jpa 多数据源 配置

1、spring-config文件配置 

1)配置了两个数据源


	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	
	
    
	
	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	

2、动态数据源路由

1)需要自定义一个 DynamicDataSource 继承AbstractRoutingDataSource 实现 determineCurrentLookupKey()的方法

package com.ibm.sc.admin.core;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {
		return DatabaseContextHolder.getCustomerType();
	}

}


	
		
			
				  
				
			
		
		
	





2、DataSourceInterceptor 数据源拦截类

package com.ibm.sc.admin.core;

import org.aspectj.lang.JoinPoint;

public class DataSourceInterceptor {

	public void setdataSourceMysql(JoinPoint jp) { 
		DatabaseContextHolder.setCustomerType("dataSourceOrder"); // dataSourceOrder 和数据源路由xml中配置的名称一致

	}
	
	public void setdataSourceOracle(JoinPoint jp) {
		DatabaseContextHolder.setCustomerType("dataSourceSupport");
	}
}

3、DatabaseContextHolder 类

package com.ibm.sc.admin.core;

public class DatabaseContextHolder {

	private static final ThreadLocal contextHolder = new ThreadLocal();

	public static void setCustomerType(String customerType) {
		contextHolder.set(customerType);
	}

	public static String getCustomerType() {
		return contextHolder.get();
	}

	public static void clearCustomerType() {
		contextHolder.remove();
	}
}


4、entityManagerFactory 配置 * 可能根据需要会有所不一样

	
		
			
		
		
		
			
				classpath*:META-INF/persistence-sc.xml 
				classpath*:META-INF/persistence-oms.xml
			
		
	

	
		
			
				
				
				
			
		
		
		
	

记录一下 以后备用


你可能感兴趣的:(Spring)