SpringBoot+Mybatis 多数据源配置

原创
2018/01/11 22:08
阅读数 652

application.properties配置文件中的配置项:

# db1
spring.datasource.db1.url=jdbc:mysql://172.17.127.164:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.db1.username=name
spring.datasource.db1.password=password
spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver
# db2
spring.datasource.db1.url=jdbc:mysql://172.17.127.164:3306/db2?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.db2.username=name
spring.datasource.db2.password=password
spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver

DataSourceConfig.java

@Configuration
public class DataSourceConfig {

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

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

}

MybatisCasesDb1Config.java

@Configuration
@MapperScan(basePackages = {"com.demo.dao.db1"}, sqlSessionFactoryRef = "sqlSessionFactoryDB1")
public class MybatisCasesDbConfig {
    @Autowired
    @Qualifier("db1")
    private DataSource db1;

    @Bean
    public SqlSessionFactory sqlSessionFactoryDB1() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(db1);
        return factoryBean.getObject();

    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateDB1() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryCases());
        return template;
    }
}

MybatisSysDb2Config.java

@Configuration
@MapperScan(basePackages = {"com.demo.dao.db2"}, sqlSessionFactoryRef = "sqlSessionFactoryDB2")
public class MybatisCasesDbConfig {
    @Autowired
    @Qualifier("db2")
    private DataSource db2;

    @Bean
    public SqlSessionFactory sqlSessionFactoryDB2() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(db2);
        return factoryBean.getObject();

    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateDB2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryCases());
        return template;
    }
}

完成....

展开阅读全文
打赏
0
5 收藏
分享
加载中
更多评论
打赏
0 评论
5 收藏
0
分享
返回顶部
顶部