mysql-plus多数据库_Springboot+mybatisplus+mysql配置多数据源(注解版)

1、添加依赖,最关键的两个依赖是后面两个"druid依赖"和"配置动态数据源"(已标红),其他"非主要"依赖可按自身实际开发环境进行选择。

org.springframework.boot

spring-boot-starter-jdbc

org.springframework.boot

spring-boot-starter-web

com.baomidou

mybatis-plus-boot-starter

3.1.1

com.baomidou

mybatis-plus-generator

3.1.1

mysql

mysql-connector-java

runtime

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-thymeleaf

net.sourceforge.nekohtml

nekohtml

org.projectlombok

lombok

1.18.8

org.freemarker

freemarker

2.3.28

com.github.pagehelper

pagehelper-spring-boot-starter

1.2.5

org.mybatis

mybatis

cn.hutool

hutool-all

5.0.7

com.alibaba

fastjson

1.2.4

com.alibaba

druid-spring-boot-starter

1.1.20

com.baomidou

dynamic-datasource-spring-boot-starter

2.5.6

2、添加数据源,在application.yml添加如下配置,其中primary: demo表示默认数据源为demo,即在不添加注解指定的情况下数据源为demo

spring:

datasource:

dynamic:

primary: demo # 配置默认数据库

datasource:

demo: # 数据源1配置

url: jdbc:mysql://localhost:3306/demo?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8

username: root

password: 123456

driver-class-name: com.mysql.cj.jdbc.Driver

test: # 数据源2配置

url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8

username: root

password: 123456

driver-class-name: com.mysql.cj.jdbc.Driver

durid:

initial-size: 1

max-active: 20

min-idle: 1

max-wait: 60000

autoconfigure:

exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置

3、启动类添加注解

在@SpringBootApplication中添加exclude = DruidDataSourceAutoConfigure.class,可取消系统自动配置数据源,这很关键,不要忘记!否则会报寻找不到"xxx" bean的错误

@MapperScan("com.xlfdy.test.mapper")

@SpringBootApplication(exclude= DruidDataSourceAutoConfigure.class)

@EnableCaching

@EnableSchedulingpublic classTestApplication {public static voidmain(String[] args) {

SpringApplication.run(TestApplication.class, args);

}

}

4、功能测试

在需要切换指定数据源的方法或类上添加@DS("xxx")注解,"xxx"表示要切换的数据源名称,当方法和类上都有该注解时,以方法上的注解为准,service和mapper、controller中都可配置该注解。

@Servicepublic class TblUserServiceImpl extends ServiceImpl implementsITblUserService {

@Override

@DS("test")publicTblUser getAllUser(Integer id) {

QueryWrapper wrapper = new QueryWrapper<>();

wrapper.eq("id",id);

TblUser user=baseMapper.selectOne(wrapper);returnuser;

}

}

5、测试结果

表结构如下

e37532e1df36351043a982da22541d3a.png

3f994285802205a898b0d6753a8b26d7.png

指定数据源调用成功!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值