项目最近需要使用多数据源,不同的mapper分别读取不同的链接,本项目使用了mybatisplus druid 来配置多数据源,基于mysql数据库。
目录
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.6</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
spring:
# 配置数据源信息
datasource:
dynamic:
# 设置默认的数据源或者数据源组
primary: master
# 严格匹配数据源,默认false,true未匹配到指定数据源时抛异常,false使用默认数据源
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/master?serverTimezone=GMT%2B8&characterEncoding=utf-8&userSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
slave:
url: jdbc:mysql://localhost:3307/slave?serverTimezone=GMT%2B8&characterEncoding=utf-8&userSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
import com.baomidou.dynamic.datasource.annotation.DS;
import com.gzmpc.print.entity.Template;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface TestMapper {
@DS("master")
public List getMaster(String parm);
@DS("slave")
public List getSlave(String parm);
}
@DS也可在mapper层、service层使用,默认的master可以不用加@DS
在事务方法内调用@DS注解的方法,@DS注解同样不生效,原因是spring只能拦截到最外层方法的@Transactional注解,此时加载该事务的数据源,在事务方法内即使调用了@DS注解的方法,获取的是外层事务的数据源,导致@DS失效。