Spring动态切换数据库以mybatis为例,hibernate同理(java配置 非xml)

动态切换数据库

1.配置数据源名常量

public class DSConst {
    public static final String LOCAL="localibdata";
    public static final String REMOTE="remoteibdata";
}

2.数据源配置及多数据源映射关系

@Bean(name = "remote2")
    public DataSource dataSource2(){
        HashMap<Object,Object> targetDataSources = new HashMap<>();//配置目标数据源
        targetDataSources.put(DSConst.LOCAL, dataSource3());
        targetDataSources.put(DSConst.REMOTE, dataSource4());
        RoutingDS routingDS = new RoutingDS();
        routingDS.setTargetDataSources(targetDataSources);
        routingDS.setDefaultTargetDataSource(dataSource3());//配置默认数据源
        return routingDS;
    }
    
    //配置数据源1
    @Bean(name = "localibdata")
    public DataSource dataSource3(){
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setUrl(url);
        dataSource.setDriver(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

//配置数据源2
    @Bean(name = "remoteibdata")
    public DataSource dataSource4(){
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setUrl(url2);
        dataSource.setDriver(driverClassName2);
        dataSource.setUsername(username2);
        dataSource.setPassword(password2);
        return dataSource;
    }

3.配置sessionfactory(此例子为mybatis)注入数据源(此例子是注入remote2数据源)

@Resource(name="remote2")
    private DataSource dataSource2;
    
    //配置SqlSessionFactory,主要提供数据源和mapper配置文件
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource2);
        factoryBean.setTypeAliasesPackage("com.hooah.entity");        //为实体类去别名
        return factoryBean;
    }

4.建立动态数据源,注意,这个类必须继承AbstractRoutingDataSource,且实现方法determineCurrentLookupKey,该方法一般返回字符串

public class RoutingDS extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        // TODO Auto-generated method stub
        return DataSourceContextHolder.getDataSourceType();
    }

}

5.最后,如何切换呢?

调用方法DataSourceContextHolder的setDataSourceType方法即可,例:

DataSourceContextHolder.setDataSourceType(DataSourceConst.TEST); 

发布了49 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/shen251515338/article/details/93173559