springboot中配置多数据源步骤如下:
1.配置datesource和template
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.mix")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
2.配置事务,sqlSessionFactory,以及sqlSessionTemplate
注意自定义的mybatis拦截器通过sqlSessionFactory配置进去
@Configuration
@MapperScan(basePackages = "xxx", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class MixSqlSessionTemplate {
@Autowired
private AutoChangeBaseNameInterceptor autoChangeBaseNameInterceptor;
@Bean(name = "primarySqlSessionFactory")
@Primary
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setPlugins(autoChangeBaseNameInterceptor);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mix/*.xml"));
return bean.getObject();
}
//配置声明式事务管理器
@Bean(name = "primaryTransactionManager")
@Primary
public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "primarySqlSessionTemplate")
@Primary
public SqlSessionTemplate primarySqlSessionTemplate(
@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
3.配置文件中配置数据源信息
#dataSource----mysql 合同信息
spring.datasource.mix.jdbc-url=xxx
spring.datasource.mix.username=xxx
spring.datasource.mix.password=xxx
spring.datasource.mix.driver-class-name=com.mysql.jdbc.Driver
4.注意扫描的xml位置,以及mapper位置,自定义的数据源需要使用jdbc-url而不是url等
如果要使用mybatis-plus 配置sqlSessionFactoryBean的时候改为MybatisSqlSessionFactoryBean 不然会出现Invalid bound statement (not found)错误
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource)
throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
// SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
return bean.getObject();
}