场景假设:现有电商业务,商品和库存分别放在不同的库
配置数据库连接
1 | app: |
添加配置类
FirstConfig
1 | @Configuration |
SecondConfig
1 | @Configuration |
dao
1 | public interface ProductMapper { |
1 | public interface StockMapper { |
xml
1 | <?xml version="1.0" encoding="UTF-8"?> |
1 | <mapper namespace="com.karonda.springboot2datasourcesmybatis.dao.second.StockMapper"> |
使用示例
1 | @Component |
注意事项
- 使用多数据源,其中一个配置类需要添加 @Primary 注解 (有且仅有一个配置类需要添加)
- 在配置类中需要同时配置 dao 层所在的包和 xml 所在的路径
总结
与 JPA 使用多数据源配置基本相同,具体可对比上一篇文章 Spring Boot 2.x 多数据源配置之 JPA 篇
参考:
Spring Boot(七):Mybatis 多数据源最简解决方案
完整代码:GitHub
本人 C# 转 Java 的 newbie, 如有错误或不足欢迎指正,谢谢