Spring Boot整合多个MyBatis数据源实战教程
在实际项目开发中,经常会遇到需要同时连接多个数据库的场景,例如读写分离架构(主库写、从库读)、多业务系统数据集成等。本文将详细讲解Spring Boot整合MyBatis实现多数据源的两种核心方案:静态多数据源(固定数据源映射)和动态多数据源(运行时切换),并提供完整的代码示例和避坑指南。
一、前期准备
1.1 开发环境
-
开发工具:IntelliJ IDEA
-
构建工具:Maven 3.6+
-
框架版本:Spring Boot 2.7.x、MyBatis 3.5.x
-
数据库:MySQL 8.0(两个独立数据库,本文以db1和db2为例)
-
连接池:HikariCP(Spring Boot默认,性能最优)
1.2 项目依赖
在pom.xml中引入核心依赖,包含Spring Boot Web、MyBatis、MySQL驱动及动态数据源专用starter(如需动态切换):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
1.3 数据库准备
创建两个独立数据库并初始化测试表,以用户表为例:
-- 数据库1:db1,存储主业务数据
CREATE DATABASE IF NOT EXISTS db1 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE db1;
CREATE TABLE IF NOT EXISTS t_user (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
age INT NOT NULL,
create_time DATETIME DEFAULT CURRENT_TIMESTAMP
);
-- 数据库2:db2,存储日志或附属业务数据
CREATE DATABASE IF NOT EXISTS db2 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE db2;
CREATE TABLE IF NOT EXISTS t_log (
id BIGINT PRIMARY KEY AUTO_INCREMENT

最低0.47元/天 解锁文章
9622

被折叠的 条评论
为什么被折叠?



