引用两个或多个数据库里的数据,项目数据库的配置方法

1、首先配置两个数据源(数据库)以及一个动态数据库:

    
    
        
        
        
        
        
        
        
    

    
    
        
        
        
        
        
        
        
    
    
    
    
        
            
                
                
            
        
        
        
    

2、sqlSessionFactory引用的数据库是动态数据库dynamicDataSource:


    
        
        
        
    

4、事务管理这里要管理的也是上面配置的dynamicDataSource动态数据库:


    
        
    

5、写两个数据源配置类DataSourceContextHolder.java和DynamicDataSource.java来配置数据源,利用ThreadLocal解决线程安全问题。

DataSourceContextHolder 类:

package com.datasource;

public class DataSourceContextHolder {
    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();
    }
}

DynamicDataSource 类继承 AbstractRoutingDataSource,并实现determineCurrentLookupKey方法:

package com.datasource;

import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

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

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        // TODO 自动生成的方法存根
        return null;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        // TODO 自动生成的方法存根
        return DataSourceContextHolder.getCustomerType();
    }

}

6、最后就可以在需要切换数据库的地方使用以下方法来切换数据库了,要切换的数据库名字即之前在配置动态数据库时给引用的数据库赋的名字:

DataSourceContextHolder.setCustomerType("要切换的数据库名字");

7、下面附上我的目录结构:


注:每次使用完切换数据库的方法后,系统会自动切换回默认数据库,不过这之间存在一点小延迟,会出现在调用完切换数据库的方法后,立刻去跳转到引用另外一个数据库数据的页面,系统还是使用着切换后的数据库。

解决办法:可以在使用完切换数据库的方法拿到需要的数据后,再次调用 DataSourceContextHolder.setCustomerType() 方法切换回接下来需要用到的数据库。

你可能感兴趣的:(sqlserver,tomcat,java)