SpringBoot + MyBatis配置连接MySQL、SQL Server、Oracle数据库_springboot 同时连接sql server与oracle
在Spring Boot中配置连接多个数据库,你需要定义多个数据源并为每个数据源创建对应的SqlSessionFactory
和MapperScanner
。以下是一个配置示例:
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.sqlserver")
public DataSource sqlServerDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.oracle")
public DataSource oracleDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource mysqlDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(mysqlDataSource);
return sessionFactory.getObject();
}
@Bean
public SqlSessionFactory sqlServerSqlSessionFactory(@Qualifier("sqlServerDataSource") DataSource sqlServerDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(sqlServerDataSource);
return sessionFactory.getObject();
}
@Bean
public SqlSessionFactory oracleSqlSessionFactory(@Qualifier("oracleDataSource") DataSource oracleDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(oracleDataSource);
return sessionFactory.getObject();
}
@Bean
public MapperScannerConfigurer mysqlMapperScannerConfigurer(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("mysqlSqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.example.mapper.mysql");
re
评论已关闭