springboot整合mybatis配置多数据源(mysql/oracle)
在Spring Boot中整合多数据源,你可以创建多个DataSource
实例,并为每个数据源配置相应的SqlSessionFactory
和MapperScannerConfigurer
。以下是一个简化的示例:
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.oracle")
public DataSource oracleDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory sqlSessionFactoryMysql(@Qualifier("mysqlDataSource") DataSource mysqlDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(mysqlDataSource);
return sessionFactory.getObject();
}
@Bean
public SqlSessionFactory sqlSessionFactoryOracle(@Qualifier("oracleDataSource") DataSource oracleDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(oracleDataSource);
return sessionFactory.getObject();
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurerMysql(@Qualifier("sqlSessionFactoryMysql") SqlSessionFactory sqlSessionFactoryMysql) {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryMysql");
mapperScannerConfigurer.setBasePackage("com.example.mapper.mysql");
return mapperScannerConfigurer;
}
@Bean
public MapperScannerConfigurer mapperScannerConfigurerOracle(@Qualifier("sqlSessionFactoryOracle") SqlSessionFactory sqlSessionFactoryOracle) {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryOracle");
mapperScannerConfigurer.setBasePackage("com.example.mapper.oracle");
return mapperScannerConfigurer;
}
}
在上述配置中,你需要在application.properties
或application.yml
中配置数据源的基本属性,例如:
spring.datasource.mysql.url=jdbc:mysql://localhost:3306/mydb
spring
评论已关闭