Spring Boot3整合MyBatisPlus实现多数据源
本文最后更新于 2025-11-11,文章内容可能已经过时。
1.导入多数据源pom依赖
<!-- 多数据源 -->
<!-- https://mvnrepository.com/artifact/com.baomidou/dynamic-datasource-spring-boot3-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<version>4.3.1</version>
</dependency>
2.配置数据库链接
spring:
datasource:
dynamic:
#主要数据库
primary: master
#严格匹配模式,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
strict: false
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/database_1?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
username: database_1
password: database_1
type: com.zaxxer.hikari.HikariDataSource
account:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/database_2?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
username: database_2
password: database_2
type: com.zaxxer.hikari.HikariDataSource
charac:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/database_3?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
username: database_3
password: database_3
type: com.zaxxer.hikari.HikariDataSource
postal:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/database_4?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8
username: database_4
password: database_4
type: com.zaxxer.hikari.HikariDataSource
3.在Mapper上标注@DS
比如我这个mapper是Account数据库
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jam.entities.gameEntities.Accounts;
import org.springframework.stereotype.Repository;
@DS("account")
@Repository
public interface AccountsMapper extends BaseMapper<Accounts> {
}
4.在启动器标注扫描Mapper
@MapperScan("com.jam.mapper.**")
@SpringBootApplication
@EnableCaching
@MapperScan("com.jam.mapper.**")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 jampang.cn
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果

