【SpringBoot DB 系列】Mybatis-Plus 多數據源配置
前面介紹了兩種 Mybatis 的數據源配置,當然也少不了 mybatis-plus
MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上只做增強不做改變,既然做增強,那多數據源這種硬性場景,肯定是有非常簡單的解決方案的
本文將實例演示 Mybatis-Plus 多數據源的配置
I. 環境准備
1. 數據庫相關
以 mysql 為例進行演示說明,因為需要多數據源,一個最簡單的 case 就是一個物理庫上多個邏輯庫,本文是基於本機的 mysql 進行操作
創建數據庫test
與 story
,兩個庫下都存在一個表money
(同名同結構表,但是數據不同哦)
CREATE TABLE `money` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL DEFAULT '' COMMENT '用戶名',
`money` int(26) NOT NULL DEFAULT '0' COMMENT '錢',
`is_deleted` tinyint(1) NOT NULL DEFAULT '0',
`create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創建時間',
`update_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新時間',
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
2. 項目環境
本項目借助SpringBoot 2.2.1.RELEASE
+ maven 3.5.3
+ IDEA
進行開發
下面是核心的pom.xml
(源碼可以再文末獲取)
<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>
配置文件信息application.yml
,請注意下面的寫法格式,如有疑問可以參考官方教程
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:
II. 項目演示
本文主要參考自 Mybatis-Plus 官方教程,如后續版本有啥變動,請以官方說明為准
https://mp.baomidou.com/guide/dynamic-datasource.html#%E6%96%87%E6%A1%A3-documentation
1. 實體類
mybatis-plus 可以借助插件實現自動生成相應的代碼,我們這里簡單自主實現測試 demo,因為兩個數據庫中表結構完全一致,所以只需要一個 Entity
@Data
@Accessors(chain = true)
@TableName(value = "money")
public class MoneyPo {
/**
* 指定自增策略
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private Long money;
@TableField("is_deleted")
private Integer isDeleted;
@TableField(value = "create_at")
private Timestamp createAt;
@TableField(value = "update_at")
private Timestamp updateAt;
}
2. Mapper 接口
數據庫操作定義接口MoneyMapper
public interface MoneyMapper extends BaseMapper<MoneyPo> {
}
對應的 xml 文件resources/mapper/money-mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.git.hui.boot.multi.datasource.mapper.MoneyMapper">
</mapper>
3. Service 接口與實現
因為兩張表,所以我們可以定義一個接口,兩個不同的實現
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 的注解@DS
,value 為前面數據源配置文件中的 key(spring.datasource.dynamic.datasource
下面的story
+ test
)
這個注解可以放在類上也可以放在方法上,方法上的優先級 > 類,所以上面的兩個 Service 實現可以改成一個
@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);
}
}
4. 測試
為簡單起見,直接在啟動類中添加寫上測試代碼
@SpringBootApplication
@MapperScan("com.git.hui.boot.multi.datasource.mapper")
public class Application {
public Application(TestMoneyServiceImpl testMoneyService, StoryMoneyServiceImpl storyMoneyService) {
List<MoneyPo> moneyPoList = testMoneyService.listByIds(Arrays.asList(1, 1000));
System.out.println(moneyPoList);
System.out.println("--------------");
moneyPoList = storyMoneyService.listByIds(Arrays.asList(1, 1000));
System.out.println(moneyPoList);
}
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
II. 其他
0. 項目
相關博文
- 【DB 系列】Mybatis 基於 AbstractRoutingDataSource 與 AOP 實現多數據源切換
- 【DB 系列】Mybatis 多數據源配置與使用
- 【DB 系列】JdbcTemplate 之多數據源配置與使用
- 【DB 系列】Mybatis-Plus 代碼自動生成
- 【DB 系列】MybatisPlus 整合篇
- 【DB 系列】Mybatis+注解整合篇
- 【DB 系列】Mybatis+xml 整合篇
源碼
- 工程:https://github.com/liuyueyi/spring-boot-demo
- 源碼: https://github.com/liuyueyi/spring-boot-demo/tree/master/spring-boot/109-multi-datasource-mybatis-plus
1. 一灰灰 Blog
盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現 bug 或者有更好的建議,歡迎批評指正,不吝感激
下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛
- 一灰灰 Blog 個人博客 https://blog.hhui.top
- 一灰灰 Blog-Spring 專題博客 http://spring.hhui.top
- 微信公眾號: 一灰灰blog