springboot+mybatis 多数据源配置

        springboot+Mybatis多数据源配置,网上的资料很多,基本思路就是配置两个DataSourceConfiguration的配置类,在配置类上通过MapperScan注解指定每个数据源配置类扫描的dao路径,不同数据源的mapper接口放在不同的包内(我的是dao下面再分两个文件,对应不同的数据源),从而实现多数据源的功能。之前参考了一些代码,遇到一些坑。

       单数据源只要在application.yml的mybatis中指定了mapper-locations: classpath:mapper/**/*.xml,springboot就会自动完成数据库的连接,但是多数据源需要手动编写SqlSessionFactory,每一个数据源配置类中都要写。SqlSessionFactoryBean中除了设置对应的dataSource外,还需要配置一个mapper xml的路径bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));这个一定要写到当前数据源指定的dao所对应的mapper路径。

 

@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
    return bean.getObject();
}

其他代码片段:

@Configuration
@MapperScan(basePackages = "com.xx.xx.dao.master",sqlSessionTemplateRef  = "masterSqlSessionTemplate")
public class DataSourceConfiguration {

@Bean(name = "masterDataSource")     //声明其为Bean实例
@Primary  //在同样的DataSource中,首先使用被标注的DataSource
public DruidDataSource dataSource() {
    DruidDataSource dataSource = new DruidDataSource();
    ...
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));
    return bean.getObject();
}

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "masterSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
            throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值