MyBatis多数据源配置

9 篇文章 0 订阅
6 篇文章 0 订阅

MyBatis多数据源配置

最近项目需求要将原来的项目迁移整合在一个项目中启动,因此需要对配置多数据源进行考察,通过查阅资料发现苞米豆有dynamic-datasource这个项目可以实现,因此尝试自己搭建一下实现功能

引入依赖

dynamic-datasource项目地址:dynamic-datasource

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>2.4.2</version>
</dependency>

添加配置

配置在dynamic下进行,其中primary必须配置,用于选择默认的数据源,这里我们选择使用db1为默认数据源

spring:
  datasource:
    dynamic:
      primary: db1
      datasource:
        db1:
          url: jdbc:mariadb://database1?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useAffectedRows=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&serverTimezone=UTC
          username: xxxx
          password: xxxx
          driver-class-name: org.mariadb.jdbc.Driver
          type: com.zaxxer.hikari.HikariDataSource
        db2:
          url: jdbc:mysql://database2/mini-dream?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useAffectedRows=true&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
          username: xxxx
          password: xxxx
          driver-class-name: org.mariadb.jdbc.Driver
          type: com.alibaba.druid.pool.DruidDataSource

使用

使用主要是通过@DS注解进行配置选择数据源,并且可以在类上进行配置。如果不使用@DS注解的类则使用primary配置的默认数据源。

使用db1数据源

@Service
@Transactional(rollbackFor = Exception.class)
@DS("db1")
public class TagServiceImpl extends BaseServiceImpl<TagMapper, SystemTagsValue> implements TagService {
}

使用db2数据源

@Service
@Transactional(rollbackFor = Exception.class)
@DS("db2")
public class ProductServiceImpl extends BaseServiceImpl<ProductMapper, Product> implements ProductService  {
}

分别调用service层方法得到结果

============db1数据源============
Product(id=1201788679127900161, sellerId=132513131, supplierId=1201788195130384385, productNo=P1912030000001, productName=英雄联盟, sellPrice=10.05, costPrice=9.05, days=3, validatedPeriod=Tue Dec 24 00:00:00 CST 2019, departType=1, type=1, status=2, isPlacedTop=false, placedTime=Thu Jan 01 00:00:00 CST 1970, remark=, isLock=false, createTime=Tue Dec 03 17:02:03 CST 2019, createBy=132513131, updateTime=Tue Dec 03 17:02:03 CST 2019, updateBy=, isDeleted=false)
=============db2数据源===========
SystemTagsValue(id=1202431422493986818, tagName=圣枪游侠, tagCode=TS1204, tagRule=, parentId=0, isNotLeaf=0, tagStatus=0, remark=, createTime=Thu Dec 05 03:27:08 CST 2019, createBy=353807608824172544, updateTime=Thu Dec 05 03:27:08 CST 2019, updateBy=, isDeleted=0)

使用过程中遇到的问题

问题1

  • 启动时报错
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class
  • 解决方案

在启动类上的SpringBootApplication注解上将DruidDataSourceAutoConfigure类排除

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)

问题2

  • 调用接口时报错
java.lang.IllegalArgumentException: Can not set final java.lang.Class field org.apache.ibatis.binding.MapperProxy.mapperInterface to com.baomidou.mybatisplus.core.override.MybatisMapperProxy
  • 解决方案
    错误原因:
@Mapper
@DS("db1") // 该注解应该加载service的实现上
public interface Repository extends BaseMapper<SystemTagsValue> {
}

在Mapper层不能加注解@DS,该注解应该加载service的实现上

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用Mybatis配置多数据源时,可以按照以下步骤进行配置。 1. 在配置文件中指定多个数据源的相关信息。比如,可以在配置文件中定义mysql数据源和Oracle数据源。 2. 创建一个配置类,用于整合Mybatis和多个数据源。在配置类中,可以使用注解@MapperScan指定Mybatis的mapper接口的扫描路径,并使用@Primary注解标注主数据源。 3. 在配置类中,可以通过注入数据源和SqlSessionFactory的方式,为每个数据源配置对应的SqlSessionFactory。同时,还可以配置多个事务管理器,并使用注解@Transactional注解标注需要事务管理的方法。 4. 在mapper接口的mapper.xml文件中,可以使用namespace指定对应的数据源,以便在使用时能够正确选择数据源。 通过以上步骤,可以实现Mybatis多数据源配置,使得项目能够同时操作多个数据库。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Mybatis配置多数据源](https://blog.csdn.net/weixin_44385360/article/details/128121969)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [mybatis多数据源配置](https://blog.csdn.net/wwwwww12432/article/details/102637703)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值