springboot配置多数据源

配置文件

 datasource:
        base:
            driver-class-name: com.mysql.jdbc.Driver
            password: root
            url: jdbc:mysql://10.10.10.236:3306/hotdog?useUnicode=true&characterEncoding=utf8&useSSL=false
            username: root
            test-on-borrow: true
            test-while-idle: true
        yr:
            driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
            password: root
            url: jdbc:sqlserver://127.0.0.1;database=smarthone_sy
            username: root
            test-on-borrow: true
            test-while-idle: true
DataSourceConfig
@Configuration
public class DataSourceConfig {

    @Bean(name = "base")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.base") // application.properteis中对应属性的前缀
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "yr")
    @ConfigurationProperties(prefix = "spring.datasource.yr") // application.properteis中对应属性的前缀
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }

}

db1

@Configuration
@MapperScan(basePackages = {"cn.xydata.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisDbAConfig {

    @Autowired
    @Qualifier("base")
    private DataSource ds1;

    @Bean
    public SqlSessionFactory sqlSessionFactory1() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds1); // 使用titan数据源, 连接titan库

        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); // 使用上面配置的Factory
        return template;
    }
}

db2

@Configuration
@MapperScan(basePackages = {"cn.xydata.mapper2"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisDbAConfig2 {

    @Autowired
    @Qualifier("yr")
    private DataSource ds1;

    @Bean
    public SqlSessionFactory sqlSessionFactory2() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds1); // 使用titan数据源, 连接titan库

        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2()); // 使用上面配置的Factory
        return template;
    }
}

最后在对应的包下放置mapper类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值