Mybatis-plus
需要添加一个依赖,这个是baomidou官方的动态数据源包
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
配置文件:
spring:
datasource:
dynamic:
primary: story #设置默认的数据源或者数据源组,默认值即为master
strict: false #设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候会抛出异常,不启动则使用默认数据源.
datasource:
story:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/story?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password:
test:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password:
还可以用@DS
在不同的类或方法中指定数据源
public interface MoneyService extends IService<MoneyPo> {
}
@Service
@DS("story")
public class StoryMoneyServiceImpl extends ServiceImpl<MoneyMapper, MoneyPo> implements MoneyService {
}
@Service
@DS("test")
public class TestMoneyServiceImpl extends ServiceImpl<MoneyMapper, MoneyPo> implements MoneyService {
}
注解生效优先级:方法>类
@Service
public class MoneyServiceImpl extends ServiceImpl<MoneyMapper, MoneyPo> implements MoneyService {
@DS("story")
public List<MoneyPo> findByStoryIds(Collection<Long> ids) {
return baseMapper.selectBatchIds(ids);
}
@DS("test")
public List<MoneyPo> findByTestIds(Collection<Long> ids) {
return baseMapper.selectBatchIds(ids);
}
}
【SpringBoot DB 系列】Mybatis-Plus 多数据源配置 - 腾讯云开发者社区-腾讯云
Mybatis
Mybatis–配置解析–配置多个环境_ML.star的博客-CSDN博客_mybatis 可以配置成适应多种环境,这种机制有助于将sql映射应用于多种数据库之中。什么标签是配