springboot+vue 架构 (三) springboot 多数据源配置

springboot里配置多数据源

写2个数据源配置类,分别指到不同的DAO操作数据库文件

mysql的

@Configuration
@MapperScan(basePackages = {"com.heeexy.example.dao.mysql"},sqlSessionFactoryRef = "mysqlsqlSessionFactory")
public class MyBatisMysqlAConfig {

   @Autowired
    @Qualifier("mysqlDataSource")
    private DataSource dataSource;
   
   @Bean
    public SqlSessionFactory mysqlsqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resource=resolver.getResources("classpath:mapper/mysql/*.xml");//对应的mybatis的文件目录
        sqlSessionFactoryBean.setMapperLocations(resource);
 
        return sqlSessionFactoryBean.getObject();
    }
   
   @Bean
    public SqlSessionTemplate mysqlsqlSession() throws Exception{
        SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(mysqlsqlSessionFactory());
 
        return sqlSessionTemplate;
    }
}

sqlService的类

@Configuration
@MapperScan(basePackages = {"com.heeexy.example.dao.paiban"},sqlSessionFactoryRef = "paibansqlSessionFactory")
public class MyBatisPaibanAConfig {

   @Autowired
    @Qualifier("paibanDataSource")
    private DataSource dataSource;
   
   @Bean
    public SqlSessionFactory paibansqlSessionFactory() throws Exception{
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resource=resolver.getResources("classpath:mapper/paiban/*.xml");//对应的mybatis的文件目录
        sqlSessionFactoryBean.setMapperLocations(resource);
 
        return sqlSessionFactoryBean.getObject();
    }
   
   @Bean
    public SqlSessionTemplate paibansqlSession() throws Exception{
        SqlSessionTemplate sqlSessionTemplate=new SqlSessionTemplate(paibansqlSessionFactory());
 
        return sqlSessionTemplate;
    }
}

 

增加一个DataSourceConfig类

@Configuration
public class DataSourceConfig {
   
   
   @Primary
    @Bean(name="mysqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource readDataSource(){
        return DataSourceBuilder.create().build();
    }
   

    @Bean(name="paibanDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.sqlservice")
    public DataSource paibanDataSource(){
        return DataSourceBuilder.create().build();
    }

}

配置文件配置不同数据源的配置

 

在操作DAO类的时候,会根据配置获取对应的dataSource,

这样就可以操作不同的数据库了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值