Springbootp配置多源数据库mysql+oracle
步骤如下:
若使用 MybatisPlus + Mysql + oracle 优先参考下方链接(终版):
链接: https://blog.csdn.net//article/details/109044657.
1. 引入相关依赖 因oracle为收费数据库,所以需要手动将jar包打入maven仓库);
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.1.0</version>
</dependency>
2. 配置yml文件;
spring:
datasource:
db1:
jdbc-url: jdbc:oracle:thin:@localhost:1521:orcl
driver-class-name: oracle.jdbc.driver.OracleDriver
username: xxx
password: xxx
db2:
jdbc-url: jdbc:mysql://localhost:3306/securitytest?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: xxx
password: xxx
3. 数据源配置;
@MapperScan注解就是指明了扫描 dao 层,并且给 dao 层注入指定的 SqlSessionTemplate。数据源配置文件为统一模板,修改参数即可。
@Configuration
@MapperScan(basePackages = "com.datasupport.securityservice.mapper.orcl", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DataSourceConfig1 {
@Bean(name = "db1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.db1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/orcl/*.xml"));
return bean.getObject();
}
@Bean(name = "db1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "db1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
4. dao和xml目录格式如下;
对应3 @MapperScan注解