首先创建一个springboot项目,pom.xml添加对应的依赖
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 动态数据源 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.4</version>
</dependency>
然后,配置文件application.yml
spring:
datasource:
dynamic:
# 默认数据库
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/dynamic_01
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
db02:
url: jdbc:mysql://localhost:3306/dynamic_02
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
添加对应的数据库,然后写对应的名字,
使用数据源的时候,在方法上添加注解 @DS("dbName"),代码如下:
@DS("db02")
@Transactional(rollbackFor = Exception.class)
public void insertDynamic02(Dynamic02DTO dynamic02DTO) {
dynamic02Mapper.insertDynamic02(dynamic02DTO);
}
这样就可以使用了。。
还有一个注意的地方就是,一个方法调用了两个数据源的方法,不能使用@Transactional,因为两个不同的库,不能使用【小白见解,不知道有没有更好的实现方法】
我在实现的时候启动报错,如下
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
在启动类添加注解
@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})
就这样解决了 哈哈