一个SpringBoot有时会设计多个数据源(多个数据库),这个时候对于数据访问就需要切换数据源,比较常用的方案是dynamic-datasource,但是这种鸡肋框架确实没有太大引入项目的必要(而且有时会出现数据源切换失败的情况),我们可以按如下方式手动配置多数据源DataSource!
Github地址:https://github.com/ashe-c0de/multiple_data_source.git # 需更改数据源配置信息(示例中使用的是Oracle + MySQL)
application.yml配置多数据源
spring:datasource:primary:url: jdbc:oracle:thin:@localhost:1522:XEusername: usernamepassword: passworddriver-class-name: oracle.jdbc.OracleDriverdruid:initial-size: 5min-idle: 5max-active: 20filters: stat,wall,log4jsecondary:url: jdbc:mysql://localhost:3306/database?serverTimezone=Asia/Shanghaiusername: usernamepassword: passworddriver-class-name: com.mysql.cj.jdbc.Driverdruid:initial-size: 5min-idle: 5max-active: 20filters: stat,wall,log4j
手动配置DataSource
@Configuration
@MapperScan(basePackages = "org.ashe.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {@Bean(name = "primaryDataSource")@ConfigurationProperties(prefix = "spring.datasource.primary")@Primarypublic DataSource primaryDataSource() {return DruidDataSourceBuilder.create().build();}@Bean(name = "primarySqlSessionFactory")@Primarypublic SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/primary/*.xml"));return bean.getObject();}
}
@Configuration
@MapperScan(basePackages = "org.ashe.mapper.secondary", sqlSessionFactoryRef = "secondarySqlSessionFactory")
public class SecondaryDataSourceConfig {@Bean(name = "secondaryDataSource")@ConfigurationProperties(prefix = "spring.datasource.secondary")public DataSource secondaryDataSource() {return DruidDataSourceBuilder.create().build();}@Bean(name = "secondarySqlSessionFactory")public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/secondary/*.xml"));return bean.getObject();}
}
如此配置后,无论是使用MybatisPlus的提供的通用CURD方法,还是自己在mapper.xml文件自定义的SQL都能按预期执行。