Spring Boot 2.x 多数据源配置之 MyBatis 篇
场景假设:现有电商业务,商品和库存分别放在不同的库
配置数据库连接
app:
datasource:
first:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1/product?useSSL=false
username: root
password: root
configuration:
maximum-pool-size: 10
second:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1/stock?useSSL=false
username: root
password: root
configuration:
maximum-pool-size: 10
添加配置类
FirstConfig
@Configuration
@MapperScan(
basePackages = {"com.karonda.springboot2datasourcesmybatis.dao.first"},// 1. dao 层所在的包
sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class FirstConfig {
@Bean
@Primary
public SqlSessionTemplate firstSqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(firstSqlSessionFactory());
}
@Bean
@Primary
public DataSourceTransactionManager firstTransactionManager(){
return new DataSourceTransactionManager(firstDataSource());
}
@Bean
@Primary
public SqlSessionFactory firstSqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(firstDataSource());
factoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/first/*.xml")); // 2. xml 所在路径
return factoryBean.getObject();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.first.configuration")
public DataSource firstDataSource() {
return firstDataSourceProperties()
.initializeDataSourceBuilder()
.type(HikariDataSource.class) // 3. 可以显示指定连接池,也可以不显示指定;即此行代码可以注释掉
.build();
}
}
SecondConfig
@Configuration
@MapperScan(
basePackages = {"com.karonda.springboot2datasourcesmybatis.dao.second"},
sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondConfig {
@Bean
public SqlSessionTemplate secondSqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(secondSqlSessionFactory());
}
@Bean
public DataSourceTransactionManager secondTransactionManager(){
return new DataSourceTransactionManager(secondDataSource());
}
@Bean
public SqlSessionFactory secondSqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(secondDataSource());
factoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/second/*.xml"));
return factoryBean.getObject();
}
@Bean
@ConfigurationProperties("app.datasource.second")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@ConfigurationProperties("app.datasource.second.configuration")
public DataSource secondDataSource() {
return secondDataSourceProperties()
.initializeDataSourceBuilder()
.type(HikariDataSource.class)
.build();
}
}
dao
public interface ProductMapper {
Product getOneById(int id);
}
public interface StockMapper {
Stock getOneByProductId(int productId);
}
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.karonda.springboot2datasourcesmybatis.dao.first.ProductMapper">
<resultMap id="BaseResultMap" type="com.karonda.springboot2datasourcesmybatis.entity.Product">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>
<sql id="Base_Column_List">
id, name
</sql>
<select id="getOneById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from product
where id = #{id,jdbcType=INTEGER}
</select>
</mapper>
<mapper namespace="com.karonda.springboot2datasourcesmybatis.dao.second.StockMapper">
<resultMap id="BaseResultMap" type="com.karonda.springboot2datasourcesmybatis.entity.Stock">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="product_id" jdbcType="INTEGER" property="productId" />
<result column="stock_count" jdbcType="INTEGER" property="stockCount" />
</resultMap>
<sql id="Base_Column_List">
id, product_id, stock_count
</sql>
<select id="getOneByProductId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from stock
where product_id = #{productId,jdbcType=INTEGER}
</select>
</mapper>
使用示例
@Component
public class Task {
@Autowired
private ProductMapper productMapper;
@Autowired
private StockMapper stockMapper;
@Scheduled(cron = "0/5 * * * * ? ")
public void job(){
final int productId = 1;
Product product = productMapper.getOneById(productId);
Stock stock = stockMapper.getOneByProductId(productId);
System.out.println("产品名称: " + product.getName() + ", 库存: " + stock.getStockCount());
}
}
注意事项
- 使用多数据源,其中一个配置类需要添加 @Primary 注解 (有且仅有一个配置类需要添加)
- 在配置类中需要同时配置 dao 层所在的包和 xml 所在的路径
总结
与 JPA 使用多数据源配置基本相同,具体可对比上一篇文章 Spring Boot 2.x 多数据源配置之 JPA 篇
参考:
Spring Boot(七):Mybatis 多数据源最简解决方案
完整代码:GitHub
本人 C# 转 Java 的 newbie, 如有错误或不足欢迎指正,谢谢
Spring Boot 2.x 多数据源配置之 MyBatis 篇的更多相关文章
- Spring Boot 2.x 多数据源配置之 JPA 篇
场景假设:现有电商业务,商品和库存分别放在不同的库 配置数据库连接 app: datasource: first: driver-class-name: com.mysql.cj.jdbc.Drive ...
- 13、Spring Boot 2.x 多数据源配置
1.13 Spring Boot 2.x 多数据源配置 完整源码: Spring-Boot-Demos
- Spring Boot之JdbcTemplate多数据源配置与使用
之前在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源.在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.propertie ...
- Spring Boot 两种多数据源配置:JdbcTemplate、Spring-data-jpa
多数据源配置 JdbcTemplate支持 Spring-data-jpa支持 多数据源配置 创建一个Spring配置类,定义两个DataSource用来读取application.propertie ...
- Spring Boot 2.x基础教程:Spring Data JPA的多数据源配置
上一篇我们介绍了在使用JdbcTemplate来做数据访问时候的多数据源配置实现.接下来我们继续学习如何在使用Spring Data JPA的时候,完成多数据源的配置和使用. 添加多数据源的配置 先在 ...
- Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源
本文是 Spring Boot 整合数据持久化方案的最后一篇,主要和大伙来聊聊 Spring Boot 整合 Jpa 多数据源问题.在 Spring Boot 整合JbdcTemplate 多数据源. ...
- Spring Boot应用的后台运行配置
酱油一篇,整理一下关于Spring Boot后台运行的一些配置方式.在介绍后台运行配置之前,我们先回顾一下Spring Boot应用的几种运行方式: 运行Spring Boot的应用主类 使用Mave ...
- Spring boot 的 properties 属性值配置 application.properties 与 自定义properties
配置属性值application.properties 文件直接配置: com.ieen.super.name="MDD" 自定义properties文件配置:src/main/r ...
- Spring Boot 启动(二) 配置详解
Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置 ...
随机推荐
- React react-redux props或state更新视图无法重新渲染问题
记录学习React时自己是如何挖坑把自己埋了的过程:children以及其它props被修改时相关组件无法重新渲染(做了两天) 父组件代码: class UserHome extends Compon ...
- OGG投递进程报错无法open文件,无法正常投递
1.1现象 之前有个客户遇到一个问题,OGG同步数据链路,突然有一天网络出现问题,导致OGG投递进程无法正常投递,无法写入目标端的该文件. 猜测是由于网络丢包等原因导致文件损坏,无法正常open,re ...
- 内网渗透 day11-免杀框架
免杀框架 目录 1. venom框架 2. shelltel框架 3. backdoor factory(BDP) 1. venom框架 cd venom进入venom文件夹中./venom.sh进入 ...
- [读书笔记] Python语言及其应用
记录下秋招期间看的一本Python工具书<Python语言与其应用>,查漏补缺,部分内容整理如下: 易混淆概念 1.1 删除 - del,remove()和pop() 1.2 复制 - 浅 ...
- jdk+tomcat 文件下载
1.下载jdk+tomcat 链接:https://pan.baidu.com/s/1DQ-l2S4th9BoucWqAymmLg :密码: zdd3 备:tomcat是解压包,直接解压就能用,但需配 ...
- 对“线上问题 不能gdb调试怎么处理??“”的思考
Q1:线上问题的process 都为release版本!不带调试信息怎么查?(目前有时需要查线上问题, 不得不解决这个问题) 之前查问题都是编译环境编译一个带有debug信息的版本进行替换来调试,但是 ...
- 一键SSH连接 = SSH密钥登陆 + WindowsTerminal
本文记录如何利用SSH密钥登录和WindowsTerminal/FluentTerminal实现一键SSH连接 目录 一.在本地生成SSH密钥对 二.在远程主机安装公钥 三.在远程主机打开密钥登陆功能 ...
- 删除osd的正确方式
在ceph的集群当中关于节点的替换的问题,一直按照以前的方式进行的处理,处理的步骤如下: 停止osd进程 /etc/init.d/ceph stop osd.0 这一步是停止osd的进程,让其他的os ...
- arm-linux校时和时钟同步
# 将时间写到系统 date 2020.08.25-14:02:00 # 将时间同步到硬件时钟芯片 hwclock -f /dev/rtc1 -w # 将时间从硬件时钟芯片同步到系统 hwclock ...
- Annotation注解初识
注解本质上就是一个接口,该接口默认继承Annotation接口 元注解 元注解的作用就是描述其他注解.Java1.5定义了4个标准的meta-annotation类型,它们被用来提供对其它 annot ...