mysql-plus多数据库_Springboot+mybatisplus+mysql配置多数据源(注解版)
1、添加依賴,最關(guān)鍵的兩個依賴是后面兩個"druid依賴"和"配置動態(tài)數(shù)據(jù)源"(已標(biāo)紅),其他"非主要"依賴可按自身實(shí)際開發(fā)環(huán)境進(jìn)行選擇。
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、添加數(shù)據(jù)源,在application.yml添加如下配置,其中primary: demo表示默認(rèn)數(shù)據(jù)源為demo,即在不添加注解指定的情況下數(shù)據(jù)源為demo
spring:
datasource:
dynamic:
primary: demo # 配置默認(rèn)數(shù)據(jù)庫
datasource:
demo: # 數(shù)據(jù)源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: # 數(shù)據(jù)源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,可取消系統(tǒng)自動配置數(shù)據(jù)源,這很關(guān)鍵,不要忘記!否則會報尋找不到"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、功能測試
在需要切換指定數(shù)據(jù)源的方法或類上添加@DS("xxx")注解,"xxx"表示要切換的數(shù)據(jù)源名稱,當(dāng)方法和類上都有該注解時,以方法上的注解為準(zhǔn),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、測試結(jié)果
表結(jié)構(gòu)如下
指定數(shù)據(jù)源調(diào)用成功!
總結(jié)
以上是生活随笔為你收集整理的mysql-plus多数据库_Springboot+mybatisplus+mysql配置多数据源(注解版)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 亚马逊Rekognition发布针对人脸
- 下一篇: Mysql索引示例_MYSQL索引实例