Mybatis-plus多數(shù)據(jù)源配置的兩種方式總結(jié)
1.多數(shù)據(jù)源配置類
整體項(xiàng)目結(jié)構(gòu)

1).pom.xml 項(xiàng)目依賴
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sz</groupId>
<artifactId>MybatisDataSourcesDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>MybatisDataSourcesDemo</name>
<description>MybatisDataSourcesDemo</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.sz.mybatisdatasourcesdemo.MybatisDataSourcesDemoApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>2)多數(shù)據(jù)源配置類
DataSource -> SqlsessionFactory -> SqlSessionTemplate
? -> DataSourceTransactionManager
(1).DS1DataSourceConfig 配置類
@MapperScan(basePackages = "com.sz.mybatisdatasourcesdemo.mapper.ds1",sqlSessionTemplateRef = "db1SqlSessionTemplate")
@Component
public class DS1DataSourceConfig {
@Bean
// 給DataSource 綁定屬性值
@ConfigurationProperties(prefix = "ds1")
//創(chuàng)建一個(gè)數(shù)據(jù)源對(duì)象 底層通過 BeanUtils.instantiateClass(type); 實(shí)例化一個(gè)數(shù)據(jù)源對(duì)象
//候選的數(shù)據(jù)源有
//"com.zaxxer.hikari.HikariDataSource",
// "org.apache.tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource"
public DataSource ds1DataSource(){
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory ds1SqlsessionFactory (
@Qualifier("ds1DataSource")DataSource dataSource
)throws Exception
{
// 工廠bean SqlSessionFactory
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//設(shè)置數(shù)據(jù)源
bean.setDataSource(dataSource);
//加載映射文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().
getResources("classpath*:mybatis/ds1/*.xml"));
return bean.getObject();
}
@Bean
// 數(shù)據(jù)源事務(wù)管理器
public DataSourceTransactionManager db1TransactionManager(@Qualifier("ds1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("ds1SqlsessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}(2).DS2DataSourceConfig 配置類
@MapperScan(basePackages = "com.sz.mybatisdatasourcesdemo.mapper.ds2",sqlSessionTemplateRef = "ds2SqlSessionTemplate")
@Component
public class DS2DataSourceConfig {
@Bean
// 給DataSource 綁定屬性值
@ConfigurationProperties(prefix = "ds2")
//創(chuàng)建一個(gè)數(shù)據(jù)源對(duì)象 底層通過 BeanUtils.instantiateClass(type); 實(shí)例化一個(gè)數(shù)據(jù)源對(duì)象
//候選的數(shù)據(jù)源有
//"com.zaxxer.hikari.HikariDataSource",
// "org.apache.tomcat.jdbc.pool.DataSource", "org.apache.commons.dbcp2.BasicDataSource"
public DataSource ds2DataSource(){
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory ds2SqlsessionFactory (
@Qualifier("ds2DataSource")DataSource dataSource
)throws Exception
{
// 工廠bean SqlSessionFactory
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
//設(shè)置數(shù)據(jù)源
bean.setDataSource(dataSource);
//加載映射文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().
getResources("classpath*:mybatis/ds2/*.xml"));
return bean.getObject();
}
@Bean
// 數(shù)據(jù)源事務(wù)管理器
public DataSourceTransactionManager ds2TransactionManager(@Qualifier("ds2DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
public SqlSessionTemplate ds2SqlSessionTemplate(@Qualifier("ds2SqlsessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}3) 多Mapper
ds1 路徑下 與 ds2 路徑下各一個(gè) mapper文件 分別由 ds1配置類 與 ds2配置類 去掃描生成代理類

4) application.properties 配置文件
用兩個(gè)數(shù)據(jù)庫模擬不同的數(shù)據(jù)源

# 應(yīng)用名稱 spring.application.name=MybatisDataSourcesDemo mybatis-plus.mapper-locations=classpath:mybatis/mapper/ds1/*.xml,classpath:mybatis/mapper/ds2/*.xml #ds1 ds1.type=com.alibaba.druid.pool.DruidDataSource ds1.jdbc-url=jdbc:mysql://localhost:3306/ds1?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL ds1.username=root ds1.password=root ds1.driver-class-name=com.mysql.cj.jdbc.Driver #ds2 ds2.type=com.alibaba.druid.pool.DruidDataSource ds2.jdbc-url=jdbc:mysql://localhost:3306/ds2?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL ds2.username=root ds2.password=root ds2.driver-class-name=com.mysql.cj.jdbc.Driver
5) 測試類
@Autowired
private AnimalService animalService;
@Autowired
private UserService userService;
@Test
void contextLoads() {
animalService.remove(null);
userService.remove(null);
Animal animal = new Animal();
animal.setName("老虎");
animalService.save(animal);
User user = new User();
user.setName("張三");
userService.save(user);
List<Animal> animals = animalService.list();
System.out.println("animals = " + animals);
List<User> userList = userService.list();
System.out.println("userList = " + userList);
}

2.@DS 注解 切換數(shù)據(jù)源
分別在 ds1和 ds2庫中添加 user 表
1) 新增依賴
版本與 mybatis-plus保存一致
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${version}</version>
</dependency>2) application.yml 配置類
spring:
datasource:
dynamic:
# primary: master #設(shè)置默認(rèn)的數(shù)據(jù)源或者數(shù)據(jù)源組,默認(rèn)值即為master
strict: false #嚴(yán)格匹配數(shù)據(jù)源,默認(rèn)false. true未匹配到指定數(shù)據(jù)源時(shí)拋異常,false使用默認(rèn)數(shù)據(jù)源
datasource:
slave_1:
url: jdbc:mysql://localhost:3306/ds1?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver # 3.2.0開始支持SPI可省略此配置
slave_2:
url: jdbc:mysql://localhost:3306/ds2?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=CONVERT_TO_NULL
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver3) 添加 @DS注解 切換數(shù)據(jù)源
@Service
public class UserServiceImpl
extends ServiceImpl<UserMapper, User>
implements UserService {
@Override
@DS("slave_1")
public List<User> findAllDS1()
{
return this.baseMapper.selectList(null);
}
@Override
@DS("slave_2")
public List<User> findAllDS2()
{
return this.baseMapper.selectList(null);
}
}
4) 測試類
@Test
void testDS()
{
List<User> allDS1 = userService.findAllDS1();
System.out.println("allDS1 = " + allDS1);
List<User> allDS2 = userService.findAllDS2();
System.out.println("allDS2 = " + allDS2);
}

到此這篇關(guān)于Mybatis-plus多數(shù)據(jù)源配置的兩種方式總結(jié)的文章就介紹到這了,更多相關(guān)Mybatis-plus多數(shù)據(jù)源配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- MyBatisPuls多數(shù)據(jù)源操作數(shù)據(jù)源偶爾報(bào)錯(cuò)問題
- Mybatis-plus配置多數(shù)據(jù)源,連接多數(shù)據(jù)庫方式
- MyBatis-Plus多數(shù)據(jù)源的示例代碼
- SpringBoot集成Mybatis實(shí)現(xiàn)對(duì)多數(shù)據(jù)源訪問原理
- Seata集成Mybatis-Plus解決多數(shù)據(jù)源事務(wù)問題
- 詳解SpringBoot Mybatis如何對(duì)接多數(shù)據(jù)源
- Mybatis操作多數(shù)據(jù)源的實(shí)現(xiàn)
- 一文搞懂MyBatis多數(shù)據(jù)源Starter實(shí)現(xiàn)
- MyBatis-Plus 集成動(dòng)態(tài)多數(shù)據(jù)源的實(shí)現(xiàn)示例
- Mybatis-Plus的多數(shù)據(jù)源你了解嗎
- mybatis-flex實(shí)現(xiàn)多數(shù)據(jù)源操作
相關(guān)文章
簡單了解Java刪除字符replaceFirst原理及實(shí)例
這篇文章主要介紹了簡單了解Java刪除字符replaceFirst原理及實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-05-05
Springboot中PropertySource的結(jié)構(gòu)與加載過程逐步分析講解
本文重點(diǎn)講解一下Spring中@PropertySource注解的使用,PropertySource主要是對(duì)屬性源的抽象,包含屬性源名稱name和屬性源內(nèi)容對(duì)象source。其方法主要是對(duì)這兩個(gè)字段進(jìn)行操作2023-01-01
springboot項(xiàng)目數(shù)據(jù)庫配置類DatabaseConfig示例詳解
這篇文章主要介紹了springboot項(xiàng)目數(shù)據(jù)庫配置類DatabaseConfig實(shí)現(xiàn)代碼,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08
Spring?Boot在啟動(dòng)時(shí)執(zhí)行一次的功能實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于Spring?Boot在啟動(dòng)時(shí)執(zhí)行一次的功能實(shí)現(xiàn),在實(shí)習(xí)過程中,有時(shí)候會(huì)遇到一些項(xiàng)目啟動(dòng)初始化的需求,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
Spring?Data?Jpa返回自定義對(duì)象的3種方法實(shí)例
在使用Spring Data Jpa框架時(shí),根據(jù)業(yè)務(wù)需求我們通常需要進(jìn)行復(fù)雜的數(shù)據(jù)庫查詢,下面這篇文章主要給大家介紹了關(guān)于Spring?Data?Jpa返回自定義對(duì)象的3種方法,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
Java用Arrays.fill()初始化二維數(shù)組的實(shí)現(xiàn)
這篇文章主要介紹了Java用Arrays.fill()初始化二維數(shù)組的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
springboot使用@KafkaListener監(jiān)聽多個(gè)kafka配置實(shí)現(xiàn)
當(dāng)服務(wù)中需要監(jiān)聽多個(gè)kafka時(shí),?需要配置多個(gè)kafka,本文主要介紹了springboot使用@KafkaListener監(jiān)聽多個(gè)kafka配置實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04

