IBATIS下多数据源切换


DynamicDataSource.java

package com.ibatis.util;

import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;


public class DynamicDataSource extends AbstractRoutingDataSource {
	
	static Logger log = Logger.getLogger("DynamicDataSource");
	
	@Override
	protected Object determineCurrentLookupKey() {
		// TODO Auto-generated method stub
		return DbContextHolder.getDbType();
	}
	
}

DbContextHolder.java

package com.ibatis.util;

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();
	}

}


调用:

	public List queryForList(String latnId,String opName,HashMap paramMap) throws SQLException{
		this.beforeExecute(latnId);
		return this.getSqlMapClient().queryForList(opName, paramMap);
	}
	
	public void beforeExecute(String latnId){
		if("888".equals(latnId)){
			DbContextHolder.setDbType("3");   
		}else{
			DbContextHolder.setDbType("1"); 
		}
	}


配置文件:


       
      
      
    
    
		
			
				
				
				
			
		
		
	 




你可能感兴趣的:(工作心得)