Mybatis-plus多数据源配置的两种方式总结
作者:秋日的晚霞 发布时间:2023-07-24 05:22:48
标签:Mybatisplus,多数据源,配置
1.多数据源配置类
整体项目结构
1).pom.xml 项目依赖
<?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)多数据源配置类
DataSource -> SqlsessionFactory -> SqlSessionTemplate
-> DataSourceTransactionManager
(1).DS1DataSourceConfig 配置类
@MapperScan(basePackages = "com.sz.mybatisdatasourcesdemo.mapper.ds1",sqlSessionTemplateRef = "db1SqlSessionTemplate")
@Component
public class DS1DataSourceConfig {
@Bean
// 给DataSource 绑定属性值
@ConfigurationProperties(prefix = "ds1")
//创建一个数据源对象 底层通过 BeanUtils.instantiateClass(type); 实例化一个数据源对象
//候选的数据源有
//"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();
//设置数据源
bean.setDataSource(dataSource);
//加载映射文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().
getResources("classpath*:mybatis/ds1/*.xml"));
return bean.getObject();
}
@Bean
// 数据源事务管理器
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")
//创建一个数据源对象 底层通过 BeanUtils.instantiateClass(type); 实例化一个数据源对象
//候选的数据源有
//"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();
//设置数据源
bean.setDataSource(dataSource);
//加载映射文件
bean.setMapperLocations(new PathMatchingResourcePatternResolver().
getResources("classpath*:mybatis/ds2/*.xml"));
return bean.getObject();
}
@Bean
// 数据源事务管理器
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 路径下各一个 mapper文件 分别由 ds1配置类 与 ds2配置类 去扫描生成代理类
4) application.properties 配置文件
用两个数据库模拟不同的数据源
# 应用名称
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 注解 切换数据源
分别在 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 #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
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.Driver
3) 添加 @DS注解 切换数据源
@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);
}
来源:https://blog.csdn.net/JAVAlife2021/article/details/127300879


猜你喜欢
- SpringMVC用Post方式重定向正常会以return "redirect:/XXX"这种方式直接重定向,但是这种方
- 具体详细介绍请看下文:在使用文件进行交互数据的应用来说,使用FTP服务器是一个很好的选择。本文使用Apache Jakarta Common
- 前言最近公司要把百度地图集成的项目中,于是我就研究了一天百度地图的SDK,当前的版本:Android SDK v3.0.0 。 虽然百度地图
- classpath读取resources目录下文件最近在springboot+maven的项目中去读取资源文件的时候,报了找不到文件的错误。
- 使用ManagedWifi查看当前Wifi信号并选择wifiusing System;using System.Collections.Ge
- 本文实例为大家分享了Java实现统计字符串出现次数的具体代码,供大家参考,具体内容如下需求:健盘录入一个字符串,要求统计字符串中每个字符串出
- 1.问题由来迷宫实验是取自心理学的一个古典实验。在该实验中,把一只老鼠从一个无顶大盒子的门放入,在盒中设置了许多墙,对行进方向形成了多处阻挡
- 前言泛型,一个孤独的守门者。大家可能会有疑问,我为什么叫做泛型是一个守门者。这其实是我个人的看法而已,我的意思是说泛型没有其看起来那么深不可
- 前言Basic编码是标准的BASE64编码,用于处理常规的需求:输出的内容不添加换行符,而且输出的内容由字母加数字组成。最近做了个Web模版
- Jfreechart本身不能生成SVG图形,但是可以借助另外一个东西,辅助生成.好像是这个:batik ,具体代码请看下文一:Java生成s
- 画廊视图(Gallery)表示,能够按水平方向显示内容,并且可用手指直接拖动图片移动,一般用来浏览图片,被选中的选项位于中间,并且可以响应事
- 1.可能是缓存导致的。解决方法:清除缓存!2.全局编译可能项目依赖别的模块,别的模块修改未进行编译,这时须先对依赖模块进行编译补充知识:ID
- 本文介绍了spring整合JMS实现同步收发消息(基于ActiveMQ的实现),分享给大家,具体如下:1. 安装ActiveMQ注意:JDK
- 从 <<Windows Forms 2.0 Programming, 2nd Edition>> &nbs
- 公司有个业务需要查出所有的用户权限分类,并将最后一层类别所包含的权限查出来。数据库说明,有一个parent_id 字段是最好的:、paren
- 本文所述为C#事务处理(Execute Transaction)的一个实例,包含了创建SqlTransaction 对象并用SqlConne
- 前言这篇文章主要介绍Spring Boot的统一功能处理模块,也是AOP的实战环节。1.用户登录权限效验在学习Spring AOP之前,用户
- 目录1、对于A、B两种排队方式,说法正确的是2、Inter-process communication (IPC) is the trans
- 前段时间写了一篇基于mybatis实现的多数据源博客。感觉不是很好,这次打算加入git,来搭建一个基于Mybatis-Plus的多数据源项目
- 下文笔者讲述maven引入本地jar包时,运行报错"java.lang.NoClassDefFoundError"的处理