1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
############## mybatisplus依赖start ###################
#mybatis-plus主要功能所在依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.4</version>
</dependency>
#快捷导出模板所需依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.4</version>
</dependency>
#快捷导出代码所需模板依赖
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.32</version>
</dependency>
#多数据源配置@DS所在
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
############## mybatisplus依赖end ###################
2.application.yml
spring:
datasource:
dynamic:
primary: db1
strict: true #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
db1:
url: jdbc:mysql://127.0.0.1:3306/xx?serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: xx
password: xx
driver-class-name: com.mysql.cj.jdbc.Driver
db2:
url: jdbc:mysql://xx:xx/xx?serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: xx
password: xx
driver-class-name: com.mysql.cj.jdbc.Driver
db3:
url: jdbc:mysql://xx:xx/dxx?serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: xx
password: xx
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initial-size: 10
max-active: 50
min-idle: 1
max-wait: 60000
autoconfigure:
#DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找 url, username, password 等,
#动态数据源 URL 等配置是在 dynamic 下,因此需要排除,否则会报错
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
3.mapper.java
@Mapper
@DS("db3") ##指定具体数据源
public interface OrganizationMapper extends BaseMapper<Organization> {
}
4.保证多数据原的事务一致性(@DSTransactional注解)
@DSTransactional
public void test() {
//db1数据源
DeAnOrganization deAnOrganization = new DeAnOrganization();
deAnOrganization.setId(1L);
deAnOrganizationMapper.insert(deAnOrganization);
//db2数据源
JdfLightBasic jdfLightBasic = new JdfLightBasic();
jdfLightBasic.setOrgId("1");
jdfLightBasicMapper.insert(jdfLightBasic);
//抛出异常,@DSTransactional可保证事务唯一性,事务可正常回滚
throw new RuntimeException("test");
}