灰常简单的配置,一看就会,一用就对
前期准备
配置相关
pom.xml
中添加依赖
<!--动态数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--oracle驱动包-->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
application.yml
中修改数据源配置
spring:
datasource:
dynamic:
primary: db1 #设置默认的数据源或者数据源组,默认值即为master
strict: true #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候回抛出异常,不启动会使用默认数据源.
datasource:
db1:
url: jdbc:mysql://***.***.***.***:3306/dbname?characterEncoding=UTF-8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username: ***
password: ***
driverClassName: com.mysql.jdbc.Driver
db2:
driverClassName: oracle.jdbc.OracleDriver
url: jdbc:oracle:thin:@***.***.***.***:1521:dbname
username: ***
password: ***
hikari:
connectionTimeout: 600000
完结!!使用方法
在需要切换数据源的类或方法上添加@DS()
注解;注解中写的内容为在application.yml
配置文件中配置的数据库名字,本例中为db1和db2
例子:
package ***.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import ***.bean.entity.EopQuestionImage;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
* @author Liu xinxing
* @since 2020-06-10
*/
@DS("db2")
//本例中配置的默认数据源为"db1" 所以,如果不加@DS注解则默认使用db1的数据源
public interface QuestionImageMapper extends BaseMapper<QuestionImage> {
List<QuestionImage> selectAll();
}
本例中配置的默认数据源
为"db1" 所以,如果不加
@DS注解则默认使用db1
的数据源