Springboot+MybatisPlus+多数据源mysql&oracle(终版)
步骤如下:
1. 引入相关依赖 因oracle为收费数据库,所以需要手动将jar包打入maven仓库):
注意,因创建Springbooot项目时选择有Mybatis,而所用MybatisPlus已经包含Mybatis,所以需将Mybatis依赖删除;
<!--Mybatis-Plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<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>
<!--DS注解-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.4</version>
</dependency>
2. 配置yml文件;
spring:
autoconfigure:
# 为了某些版本的springboot @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) 无法生效
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
datasource:
dynamic:
primary: master
datasource:
master:
url: jdbc:mysql://localhost:3306/xxxx?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: xxxx
password: xxxx
local:
url: jdbc:oracle:thin:@localhost:1521:xxxx
driver-class-name: oracle.jdbc.driver.OracleDriver
username: xxxx
password: xxxx
3. Springboot启动类如下:只需配置扫描对应mapper即可;
4. 使用方式如下:只需在service添加@Ds注解指定使用数据源即可,默认数据源无需添加。;
补充内容5: 关于配置数据库url 中 ‘:’ 和 ‘/’ 的区别以及各自含义。
摘自以下链接: https://blog.csdn.net/yc123185389/article/details/72731438
格式一: 使用service_name,配置方式。
jdbc:oracle:thin:@//host:port/service_name
Example: jdbc:oracle:thin:@//localhost:1521/service_name
注意这里的格式,@后面有//, 这是与使用SID的主要区别。
这种格式是Oracle 推荐的格式,因为对于集群来说,每个节点的SID 是不一样的,但是SERVICE_NAME 确可以包含所有节点。
格式二: 使用SID,配置方式。
jdbc:oracle:thin:@host:port:SID
Example: jdbc:oracle:thin:localhost:1521:SID