Spring+mybatisplus 多数据源

本文案例为 sql server,其他数据源切换为相应的驱动即可。

依赖

<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version>
<exclusions>
<exclusion>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>

配置

# mybatis
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
spring.datasource:
dynamic:
primary: db1
datasource:
db1:
url: jdbc:sqlserver://****;
username: ****
password: ****
db2:
url: jdbc:sqlserver://****;
username: ****
password: ****

代码

xml文件省略,保持和mybatis一样即可,代码使用上只用在Mapper或者DAO文件上使用@DS声明即可。

@Mapper
@DS("db2")
public interface BehaviorEmailDao extends BaseMapper<BehaviorEmail> {
Set<String> getSendRecordByDate(@Param("lastDate") String lastDate);
}

默认主库为db1,因此操作db1的接口可不用声明。