mybatis-plus多数据源使用

首先创建一个springboot项目,pom.xml添加对应的依赖

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>

        <!-- 动态数据源 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>2.5.4</version>
        </dependency>

然后,配置文件application.yml

 

spring:
  datasource:
    dynamic:
      # 默认数据库
      primary: master
      strict: false
      datasource:
        master:
          url: jdbc:mysql://localhost:3306/dynamic_01
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver
        db02:
          url: jdbc:mysql://localhost:3306/dynamic_02
          username: root
          password: root
          driver-class-name: com.mysql.jdbc.Driver
          type: com.alibaba.druid.pool.DruidDataSource

添加对应的数据库,然后写对应的名字,

 

使用数据源的时候,在方法上添加注解 @DS("dbName"),代码如下:

    @DS("db02")
    @Transactional(rollbackFor = Exception.class)
    public void insertDynamic02(Dynamic02DTO dynamic02DTO) {
        dynamic02Mapper.insertDynamic02(dynamic02DTO);
    }

这样就可以使用了。。

还有一个注意的地方就是,一个方法调用了两个数据源的方法,不能使用@Transactional,因为两个不同的库,不能使用【小白见解,不知道有没有更好的实现方法】

我在实现的时候启动报错,如下

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


Action:

Consider the following:
	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

在启动类添加注解 

@SpringBootApplication(exclude = {DruidDataSourceAutoConfigure.class})

就这样解决了 哈哈

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值