當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【SpringBoot DB 系列】Mybatis-Plus 多数据源配置
生活随笔
收集整理的這篇文章主要介紹了
【SpringBoot DB 系列】Mybatis-Plus 多数据源配置
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
MyBatis-Plus (opens new window)(簡稱 MP)是一個 MyBatis (opens new window)的增強工具,在 MyBatis 的基礎上只做增強不做改變,既然做增強,那多數(shù)據(jù)源這種硬性場景,肯定是有非常簡單的解決方案的
本文將實例演示 Mybatis-Plus 多數(shù)據(jù)源的配置
I. 環(huán)境準備
1. 數(shù)據(jù)庫相關
一個oracle,一個sqlserver
2. 相關配置
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>org.springblade</groupId><artifactId>spd-hisserview-ymf</artifactId><version>0.0.1-SNAPSHOT</version><name>spd-hisserview-ymf</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><!-- 多數(shù)據(jù)源配置--><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.3.1</version></dependency><!-- mysql依賴--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- 引入 redis 依賴 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><!-- 默認指定了lettuce,我們需要排除 ,并且引入jedis的客戶端--><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions></dependency><!-- jedis的客戶端 --><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency><!--sqlserver數(shù)據(jù)庫JDBC連接依賴--><dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>sqljdbc4</artifactId><version>4.0</version></dependency><!--MyBatisPlus啟動依賴--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></dependency><!--Oracle數(shù)據(jù)庫JDBC連接依賴--><dependency><groupId>com.oracle</groupId><artifactId>ojdbc7</artifactId><version>12.2.0.1</version></dependency><!--JUNIT測試相關--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>配置文件信息application.yml,請注意下面的寫法格式,如有疑問可以參考官方教程
server:port: 81spring:redis:#Redis配置host: 127.0.0.1##redis端口號port: 6379##redis密碼password:##redis連接超時時間(毫秒)timeout: 60000##Redis默認情況下有16個分片,這里配置具體使用的分片,默認時0database: 10application:name: viewServicedatasource:dynamic:primary: bdsz #設置默認的數(shù)據(jù)源或者數(shù)據(jù)源組,默認值即為masterstrict: true #設置嚴格模式,默認false不啟動. 啟動后在未匹配到指定數(shù)據(jù)源時候會拋出異常,不啟動則使用默認數(shù)據(jù)源.datasource:bdsz:driver-class-name: oracle.jdbc.driver.OracleDriver# 本地連接url: jdbc:oracle:thin:@//localhost:1521/orclusername: SYSTEMpassword: 961008Dyh# 遠程連接 # url: jdbc:oracle:thin:@//100.100.100.45:1521/PDBORCL # username: BDFPQS # password: BDFPQS123456szey:driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver# 本地連接url: jdbc:sqlserver://localhost:1433;databaseName=testusername: sapassword: 961008# 遠程連接 # url: jdbc:sqlserver://192.168.170.186:1433;databaseName=HERP # username: hrp_ymf # password: hrp_ymf#mybatis-plus配置控制臺打印完整帶參數(shù)SQL語句 mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpltenantId:szey: 100000bdsz: 200000II. 代碼實現(xiàn)
1. 實體類
HisserVice
package org.springblade.entity;import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data;import java.io.Serializable;/*** 實體類** @ClassName: HisserVice* @author: 〆、風神* @since: 2022/1/27 21:25*/ @Data @TableName("SPD_HISSERVICE_YMF") @JsonInclude(JsonInclude.Include.NON_NULL) public class HisserVice implements Serializable {private static final long serialVersionUID = 1L;/*** 主鍵*/@TableId(value = "ID", type = IdType.AUTO)@JsonSerialize(using = ToStringSerializer.class)private Long id;/*** 采購訂單號*/@TableField(value = "ORDER_ID")private String orderId;/*** 采購訂單明細號*/@TableField(value = "ORDER_DETAIL_ID")private String orderDetailId;/*** 月結(jié)單號*/@TableField(value = "LUNAR_KNOT_NO")private String lunarKnotNo;/*** 月結(jié)月份*/@TableField(value = "LUNAR_KNOT_MONTH")private String lunarKnotMonth;/*** 發(fā)票號*/@TableField(value = "INVOICE_NO")private String invoiceNo;/*** 供應商*/@TableField(value = "SUPPLIER")private String supplier;/*** 品種編碼*/@TableField(value = "VARIETIES_CODE")private String varietiesCode;/*** 品種全稱*/@TableField(value = "VARIETIES_DESC")private String varietiesDesc;/*** 型號/規(guī)格*/@TableField(value = "SPEC")private String spec;/*** 單位*/@TableField(value = "UNIT")private String unit;/*** 單價*/@TableField(value = "PRICE")private String price;/*** 數(shù)量*/@TableField(value = "AMOUNT")private String amount;/*** 金額*/@TableField(value = "TOTAL_MONTY")private String totalMonty;/*** 生產(chǎn)企業(yè)*/@TableField(value = "MNUFACTURER")private String mnufacturer;/*** 批號*/@TableField(value = "BATCH")private String batch;/*** 生產(chǎn)日期*/@TableField(value = "PRODUCTION_DATE")private String productionDate;/*** 失效期*/@TableField(value = "EXPIRATION_DATE")private String expirationDate;/*** 來源*/@TableField(value = "SOURCE")private String source;/*** 高低值*/@TableField(value = "CONSUMABLE_TYPE")private String consumableType;/*** 陽光產(chǎn)品碼*/@TableField(value = "PRODUCTION")private String production;/*** 陽光規(guī)格型號碼*/@TableField(value = "SPEC_NO")private String specNo;@TableField(exist = false)private String tenantId; }MateOrderMainYmf
package org.springblade.entity;import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data;import java.io.Serializable;/*** 實體類** @ClassName: MateOrderMainYmf* @author: 〆、dyh* @since: 2022/4/1 18:27*/ @Data @TableName("mate_order_main_ymf") @JsonInclude(JsonInclude.Include.NON_NULL) public class MateOrderMainYmf implements Serializable {private static final long serialVersionUID = 1L;@TableField(value = "order_id")private String orderId;@TableField(value = "distributeAddress")private String distributeAddress;@TableField(value = "remarks")private String remarks;@TableField(value = "order_detail_id")private String orderDetailId;@TableField(value = "goodsID")private String goodsID;@TableField(value = "goodsname")private String goodsname;@TableField(value = "companyIdPs")private String companyIdPs;@TableField(value = "purchaseCount")private String purchaseCount;@TableField(value = "subcodeId")private String subcodeId;@TableField(value = "orderDetailRemark")private String orderDetailRemark;@TableField(value = "orderCustomInfo")private String orderCustomInfo;@TableField(value = "sunPlatCode")private String sunPlatCode;@TableField(value = "sunPlatSpec")private String sunPlatSpec;@TableField(value = "orderDept")private String orderDept;@TableField(value = "updateDate")private String updateDate;@TableField(value = "updateTime")private String updateTime;@TableField(exist = false)private String tenantId;}2. Mapper 接口
HisserViceMapper
package org.springblade.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.springblade.entity.HisserVice;/*** @ClassName: HisserViceMapper* @author: 〆、風神* @since: 2022/1/27 23:09*/ @Mapper public interface HisserViceMapper extends BaseMapper<HisserVice> {}MateOrderMainYmfMapper
package org.springblade.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; import org.springblade.entity.MateOrderMainYmf;/*** @InterfaceName: MateOrderMainYmfMapper* @author: 〆、dyh* @since: 2022/4/1 18:51*/ @Mapper public interface MateOrderMainYmfMapper extends BaseMapper<MateOrderMainYmf> { }3. Service 接口與實現(xiàn)
@DS注解:value 為前面數(shù)據(jù)源配置文件中的 key(spring.datasource.dynamic.datasource下面的bdsz+ szey)
這個注解可以放在類上也可以放在方法上,方法上的優(yōu)先級 > 類
HisserViceService
package org.springblade.service;import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.IService; import org.springblade.entity.HisserVice;import java.util.List;/*** @ClassName: HisserViceService* @author: 〆、風神* @since: 2022/1/27 23:07*/ public interface HisserViceService extends IService<HisserVice> {/*** 分頁查詢** @param page* @param lunarKnotMonth* @return*/IPage<HisserVice> selectList(Page<HisserVice> page, String lunarKnotMonth);/*** 不分頁查詢** @param lunarKnotMonth* @return*/List<HisserVice> selectList(String lunarKnotMonth); }MateOrderMainYmfService
package org.springblade.service;import com.baomidou.mybatisplus.extension.service.IService; import org.springblade.entity.MateOrderMainYmf;import java.util.List;/*** @InterfaceName: MateOrderMainYmfService* @author: 〆、dyh* @since: 2022/4/2 9:14*/public interface MateOrderMainYmfService extends IService<MateOrderMainYmf> {/*** 不分頁查詢** @return*/List<MateOrderMainYmf> selectList(); }HisserViceServiceImpl
package org.springblade.service.impl;import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springblade.entity.HisserVice; import org.springblade.mapper.HisserViceMapper; import org.springblade.service.HisserViceService; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils;import java.util.List;/*** @ClassName: HisserViceServiceImpl* @author: 〆、風神* @since: 2022/1/27 23:09*/ @Service @DS("bdsz") public class HisserViceServiceImpl extends ServiceImpl<HisserViceMapper, HisserVice> implements HisserViceService {@Value("${tenantId.bdsz}")private String tenantId;private static Logger logger = LoggerFactory.getLogger(HisserViceServiceImpl.class);@Overridepublic IPage<HisserVice> selectList(Page<HisserVice> page, String lunarKnotMonth) {QueryWrapper<HisserVice> queryWrapper = new QueryWrapper();if (StringUtils.hasText(lunarKnotMonth)) {queryWrapper.eq("LUNAR_KNOT_MONTH", lunarKnotMonth);}return page(page, queryWrapper);}@Overridepublic List<HisserVice> selectList(String lunarKnotMonth) {QueryWrapper<HisserVice> queryWrapper = new QueryWrapper();if (StringUtils.hasText(lunarKnotMonth)) {queryWrapper.eq("LUNAR_KNOT_MONTH", lunarKnotMonth);}return list(queryWrapper);} }MateOrderMainYmfServiceImpl
package org.springblade.service.impl;import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springblade.constant.Constant; import org.springblade.entity.MateOrderMainYmf; import org.springblade.mapper.MateOrderMainYmfMapper; import org.springblade.service.MateOrderMainYmfService; import org.springblade.util.RedisUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils;import java.util.List;/*** @ClassName: MateOrderMainYmfServiceImpl* @author: 〆、dyh* @since: 2022/4/2 9:20*/ @Service @DS("szey") public class MateOrderMainYmfServiceImpl extends ServiceImpl<MateOrderMainYmfMapper, MateOrderMainYmf> implements MateOrderMainYmfService {private static Logger logger = LoggerFactory.getLogger(MateOrderMainYmfServiceImpl.class);@Value("${tenantId.szey}")private String tenantId;@AutowiredRedisUtil redisUtil;@Overridepublic List<MateOrderMainYmf> selectList() {QueryWrapper<MateOrderMainYmf> queryWrapper = new QueryWrapper();if (redisUtil.exists(Constant.MOMYUT)) {logger.info("redis緩存的最近的修改時間:{}", redisUtil.get(Constant.MOMYUT));queryWrapper.gt("updateTime", redisUtil.get(Constant.MOMYUT));}queryWrapper.orderByDesc("updateTime");List<MateOrderMainYmf> list = list(queryWrapper);if (!CollectionUtils.isEmpty(list)) {logger.info("視圖中最近的修改時間:{}", list.get(0).getUpdateTime());redisUtil.set(Constant.MOMYUT, list.get(0).getUpdateTime());}return list;}}總結(jié)
以上是生活随笔為你收集整理的【SpringBoot DB 系列】Mybatis-Plus 多数据源配置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安全运营四要素之资产、脆弱性、威胁和事件
- 下一篇: pycharm 自定义区域折叠代码