MyBatis配置多数据源,并实现手动切换

  • Spring配置文件


    
    
        
    
    
    
        
        
        
        
    
    
        
        
        
        
    
    
        
        
            
                
                
            
        
    
    
    
        
    
    
    
        
    
    
    
    
  • 自定义MultipleDataSource实现类
package com.cnblogs.lzrabbit;

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

public class MultipleDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal dataSourceKey = new InheritableThreadLocal();

    public static void setDataSourceKey(String dataSource) {
        dataSourceKey.set(dataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return dataSourceKey.get();
    }
}
  • 手动切换数据源
package com.cnblogs.lzrabbit;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        //初始化ApplicationContext
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

        MySqlMapper mySqlMapper = applicationContext.getBean(MySqlMapper.class);

        SqlServerMapper sqlServerMapper = applicationContext.getBean(SqlServerMapper.class);
        
        //设置数据源为MySql
        MultipleDataSource.setDataSourceKey("mySqlDataSource");
        mySqlMapper.getList();
        //设置数据源为SqlServer
        MultipleDataSource.setDataSourceKey("sqlServerDataSource");
        sqlServerMapper.getList();
    }
}
转载:http://www.cnblogs.com/lzrabbit/p/3750803.html

你可能感兴趣的:(数据库)