场景假设:现有电商业务,商品和库存分别放在不同的库

配置数据库连接

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());
} }

注意事项

  1. 使用多数据源,其中一个配置类需要添加 @Primary 注解 (有且仅有一个配置类需要添加)
  2. 在配置类中需要同时配置 dao 层所在的包和 xml 所在的路径

总结

与 JPA 使用多数据源配置基本相同,具体可对比上一篇文章 Spring Boot 2.x 多数据源配置之 JPA 篇

参考:

Spring Boot(七):Mybatis 多数据源最简解决方案

完整代码:GitHub

本人 C# 转 Java 的 newbie, 如有错误或不足欢迎指正,谢谢

Spring Boot 2.x 多数据源配置之 MyBatis 篇的更多相关文章

  1. Spring Boot 2.x 多数据源配置之 JPA 篇

    场景假设:现有电商业务,商品和库存分别放在不同的库 配置数据库连接 app: datasource: first: driver-class-name: com.mysql.cj.jdbc.Drive ...

  2. 13、Spring Boot 2.x 多数据源配置

    1.13 Spring Boot 2.x 多数据源配置 完整源码: Spring-Boot-Demos

  3. Spring Boot之JdbcTemplate多数据源配置与使用

    之前在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源.在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.propertie ...

  4. Spring Boot 两种多数据源配置:JdbcTemplate、Spring-data-jpa

    多数据源配置 JdbcTemplate支持 Spring-data-jpa支持 多数据源配置 创建一个Spring配置类,定义两个DataSource用来读取application.propertie ...

  5. Spring Boot 2.x基础教程:Spring Data JPA的多数据源配置

    上一篇我们介绍了在使用JdbcTemplate来做数据访问时候的多数据源配置实现.接下来我们继续学习如何在使用Spring Data JPA的时候,完成多数据源的配置和使用. 添加多数据源的配置 先在 ...

  6. Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源

    本文是 Spring Boot 整合数据持久化方案的最后一篇,主要和大伙来聊聊 Spring Boot 整合 Jpa 多数据源问题.在 Spring Boot 整合JbdcTemplate 多数据源. ...

  7. Spring Boot应用的后台运行配置

    酱油一篇,整理一下关于Spring Boot后台运行的一些配置方式.在介绍后台运行配置之前,我们先回顾一下Spring Boot应用的几种运行方式: 运行Spring Boot的应用主类 使用Mave ...

  8. Spring boot 的 properties 属性值配置 application.properties 与 自定义properties

    配置属性值application.properties 文件直接配置: com.ieen.super.name="MDD" 自定义properties文件配置:src/main/r ...

  9. Spring Boot 启动(二) 配置详解

    Spring Boot 启动(二) 配置详解 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Boot 配置 ...

随机推荐

  1. Serilog 源码解析——Sink 的实现

    在上一篇中,我们简单地查看了 Serilog 的整体需求和大体结构.从这一篇开始,本文开始涉及 Serilog 内的相关实现,着重解决第一个问题,即 Serilog 向哪里写入日志数据的.(系列目录) ...

  2. 【SpringBoot】16. 如何监控springboot的健康状况

    如何监控springboot的健康状况 SpringBoot1.5.19.RELEASE 一.使用Actuator检查与监控 actuaotr是spring boot项目中非常强大的一个功能,有助于对 ...

  3. MYSQL的添加字段和修改字段

    ALTER TABLE 表名 ADD 字段名 字段类型 //添加字段 DESC 表名 //获取表的结构 SHOW COLUMNS FROM 表名 //也是获取表的结构 DESCRIBE 表名 //获取 ...

  4. 部署Dotnet Core应用到Kubernetes(一)

    最近闲了点,写个大活:部署Dotnet应用到K8s.   写在前边的话 一直想完成这个主题.但这个主题实在太大了,各种拖延症的小宇宙不时爆发一下,结果就拖到了现在.   这个主题,会是一个系列.在这个 ...

  5. LeetCode-680-验证回文字符串 Ⅱ

    给定一个非空字符串 s,最多删除一个字符.判断是否能成为回文字符串. image.png 解题思路: 判断是否回文字符串:isPalindrome = lambda x: x==x[::-1],即将字 ...

  6. MYSQL学习(二) --MYSQL框架

    MYSQL架构理解 通过对MYSQL重要的几个属性的理解,建立一个基本的MYSQL的知识框架.后续再补充完善. 一.MYSQL架构 这里给的架构描述,是很宏观的架构.有助于建立对MYSQL整体理解. ...

  7. 安全也挺让人心烦的 ---login shell

    今天查问题时, ssh 登录后台发现 需要输入密码,输入密码后弹出一个二维码, 然后扫码获取秘钥.输入秘钥登陆!!! 真是恶心了一把,找手机都花了不少时间!!!! 那么怎样干掉输入密码这些操作呢??? ...

  8. 利用c++ std::getline实现split

    getline reads characters from an input stream and places them into a string: getline从输入流中读取字符, 并把它们转 ...

  9. Mysql之存储过程与存储函数

    1 存储过程 1.1 什么是存储过程 存储过程是一组为了完成某项特定功能的sql语句集,其实质上就是一段存储在数据库中的代码,他可以由声明式的sql语句(如CREATE,UPDATE,SELECT等语 ...

  10. Innodb之线程独享内存

    引用链接: https://blog.csdn.net/miyatang/article/details/54881547 https://blog.csdn.net/wyzxg/article/de ...