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); }
}