Springboot 封裝整活 Mybatis 動態查詢條件SQL自動組裝拼接

前言

ps:最近在參與3100保衛戰,戰況很激烈,剛剛打完仗,來更新一下之前寫了一半的博客。

該篇針對日常寫查詢的時候,那些動態條件sql 做個簡單的封裝,自動生成(拋磚引玉,搞個小玩具,不喜勿噴)。

正文

來看看我們平時寫那些查詢,基本上都要寫的一些動態sql:
?

?

?

一個字段寫一個if ,有沒有人覺得煩的。

每張表的查詢,很多都有這種需求,根據什么查詢,根據什么查詢,不為空就觸發條件。

天天寫天天寫,copy 改,copy改, 有沒有人覺得煩的。


?

可能有看官看到這就會說, 用插件自動生成就好了。
也有看官會說,用mybatis-plus就好了。

確實有道理,但是我就是想整個小玩具。你管我。

開整

本篇實現的封裝小玩具思路:

①制定的規則(比如標記自定義注解 @JcSqlQuery 或是 函數命名帶上JcDynamics)。

② 觸發的查詢符合規則的, 都自動去根據傳參對象,不為空就自動組裝 sql查詢條件。

③ 利用mybatis @Select 注解,把默認表查詢sql寫好,順便進到自定義的mybatis攔截器里面。

④組裝完sql,就執行,完事。

先寫mapper函數 :
?

/*** @Author JCccc* @Description* @Date 2023/12/14 16:56*/
@Mapper
public interface DistrictMapper {@Select("select code,name,parent_code,full_name  FROM s_district_info")List<District> queryListJcDynamics(District district);@Select("select code,name,parent_code,full_name  FROM s_district_info")District queryOneJcDynamics(District district);}

?

然后是ParamClassInfo.java 這個用于收集需要參與動態sql組裝的類:

?

import lombok.Data;/*** @Author JCccc* @Description* @Date 2021/12/14 16:56*/
@Data
public class ParamClassInfo {private  String classType;private  Object keyValue;private  String  keyName;}

然后是一個自定義的mybatis攔截器(這里面寫了一些小函數實現自主組裝,下面有圖解) :


MybatisInterceptor.java

import com.example.dotest.entity.ParamClassInfo;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import static java.util.regex.Pattern.*;/*** @Author JCccc* @Description* @Date 2021/12/14 16:56*/
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MybatisInterceptor implements Interceptor {private final static String JC_DYNAMICS = "JcDynamics";@Overridepublic Object intercept(Invocation invocation) throws Throwable {//獲取執行參數Object[] objects = invocation.getArgs();MappedStatement ms = (MappedStatement) objects[0];Object objectParam = objects[1];List<ParamClassInfo> paramClassInfos = convertParamList(objectParam);String queryConditionSqlScene = getQueryConditionSqlScene(paramClassInfos);//解析執行sql的map方法,開始自定義規則匹配邏輯String mapperMethodAllName = ms.getId();int lastIndex = mapperMethodAllName.lastIndexOf(".");String mapperClassStr = mapperMethodAllName.substring(0, lastIndex);String mapperClassMethodStr = mapperMethodAllName.substring((lastIndex + 1));Class<?> mapperClass = Class.forName(mapperClassStr);Method[] methods = mapperClass.getMethods();for (Method method : methods) {if (method.getName().equals(mapperClassMethodStr) && mapperClassMethodStr.contains(JC_DYNAMICS)) {BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);String originalSql = boundSql.getSql().toLowerCase(Locale.CHINA).replace("[\\t\\n\\r]", " ");//進行自動的 條件拼接String newSql = originalSql + queryConditionSqlScene;BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql,boundSql.getParameterMappings(), boundSql.getParameterObject());MappedStatement newMs = newMappedStatement(ms, new MyBoundSqlSqlSource(newBoundSql));for (ParameterMapping mapping : boundSql.getParameterMappings()) {String prop = mapping.getProperty();if (boundSql.hasAdditionalParameter(prop)) {newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));}}Object[] queryArgs = invocation.getArgs();queryArgs[0] = newMs;System.out.println("打印新SQL語句" + newSql);}}//繼續執行邏輯return invocation.proceed();}private String getQueryConditionSqlScene(List<ParamClassInfo> paramClassInfos) {StringBuilder conditionParamBuilder = new StringBuilder();if (CollectionUtils.isEmpty(paramClassInfos)) {return "";}conditionParamBuilder.append("  WHERE ");int size = paramClassInfos.size();for (int index = 0; index < size; index++) {ParamClassInfo paramClassInfo = paramClassInfos.get(index);String keyName = paramClassInfo.getKeyName();//默認駝峰拆成下劃線 ,比如 userName -》 user_name ,   name -> name//如果是需要取別名,其實可以加上自定義注解這些,但是本篇例子是輕封裝,思路給到,你們i自己玩String underlineKeyName = camelToUnderline(keyName);conditionParamBuilder.append(underlineKeyName);Object keyValue = paramClassInfo.getKeyValue();String classType = paramClassInfo.getClassType();//其他類型怎么處理 ,可以按照類型區分 ,比如檢測到一組開始時間,Date 拼接 between and等
//            if (classType.equals("String")){
//                conditionParamBuilder .append("=").append("\'").append(keyValue).append("\'");
//            }conditionParamBuilder.append("=").append("\'").append(keyValue).append("\'");if (index != size - 1) {conditionParamBuilder.append(" AND ");}}return conditionParamBuilder.toString();}private static List<ParamClassInfo> convertParamList(Object obj) {List<ParamClassInfo> paramClassList = new ArrayList<>();for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(obj.getClass())) {if (!"class".equals(pd.getName())) {if (ReflectionUtils.invokeMethod(pd.getReadMethod(), obj) != null) {ParamClassInfo paramClassInfo = new ParamClassInfo();paramClassInfo.setKeyName(pd.getName());paramClassInfo.setKeyValue(ReflectionUtils.invokeMethod(pd.getReadMethod(), obj));paramClassInfo.setClassType(pd.getPropertyType().getSimpleName());paramClassList.add(paramClassInfo);}}}return paramClassList;}public static String camelToUnderline(String line){if(line==null||"".equals(line)){return "";}line=String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));StringBuffer sb=new StringBuffer();Pattern pattern= compile("[A-Z]([a-z\\d]+)?");Matcher matcher=pattern.matcher(line);while(matcher.find()){String word=matcher.group();sb.append(word.toUpperCase());sb.append(matcher.end()==line.length()?"":"_");}return sb.toString();}@Overridepublic Object plugin(Object o) {//獲取代理權if (o instanceof Executor) {//如果是Executor(執行增刪改查操作),則攔截下來return Plugin.wrap(o, this);} else {return o;}}/*** 定義一個內部輔助類,作用是包裝 SQL*/class MyBoundSqlSqlSource implements SqlSource {private BoundSql boundSql;public MyBoundSqlSqlSource(BoundSql boundSql) {this.boundSql = boundSql;}@Overridepublic BoundSql getBoundSql(Object parameterObject) {return boundSql;}}private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {MappedStatement.Builder builder = newMappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());builder.resource(ms.getResource());builder.fetchSize(ms.getFetchSize());builder.statementType(ms.getStatementType());builder.keyGenerator(ms.getKeyGenerator());if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {builder.keyProperty(ms.getKeyProperties()[0]);}builder.timeout(ms.getTimeout());builder.parameterMap(ms.getParameterMap());builder.resultMaps(ms.getResultMaps());builder.resultSetType(ms.getResultSetType());builder.cache(ms.getCache());builder.flushCacheRequired(ms.isFlushCacheRequired());builder.useCache(ms.isUseCache());return builder.build();}@Overridepublic void setProperties(Properties properties) {//讀取mybatis配置文件中屬性}

代碼簡析:

駝峰轉換下劃線,用于轉出數據庫表的字段 :

通過反射把 sql入參的對象 不為空的屬性名和對應的值,拿出來:

?

組件動態查詢的sql 語句 :

?

寫個簡單測試用例:

    @AutowiredDistrictMapper districtMapper;@Testpublic void test() {District query = new District();query.setCode("110000");query.setName("北京市");District district = districtMapper.queryOneJcDynamics(query);System.out.println(district.toString());District listQuery = new District();listQuery.setParentCode("110100");List<District> districts = districtMapper.queryListJcDynamics(listQuery);System.out.println(districts.toString());}

?看下效果,可以看到都自動識別把不為空的字段屬性和值拼接成查詢條件了:

?

?

?

好了,該篇就到這。 拋磚引玉,領悟分步封裝思路最重要,都去搞些小玩具娛樂娛樂吧。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/41588.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/41588.shtml
英文地址,請注明出處:http://en.pswp.cn/news/41588.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

chatgpt多個key循環使用解決token限速

itertools.cycle 是 Python 標準庫中的一個函數&#xff0c;它用于創建一個無限循環迭代器。它接受一個可迭代對象作為參數&#xff0c;并會不斷重復該可迭代對象的元素。 使用 itertools.cycle 可以方便地創建一個可以無限循環的迭代器。當你需要反復訪問一個可迭代對象的元素…

【Linux操作系統】深入探索Linux進程:創建、共享與管理

進程的創建是Linux系統編程中的重要概念之一。在本節中&#xff0c;我們將介紹進程的創建、獲取進程ID和父進程ID、進程共享、exec函數族、wait和waitpid等相關內容。 文章目錄 1. 進程的創建1.1 函數原型和返回值1.2 函數示例 2. 獲取進程ID和父進程ID2.1 函數原型和返回值2.…

接口測試及接口抓包常用測試工具和方法?

作為測試領域中不可或缺的一環&#xff0c;接口測試和抓包技術在軟件開發過程中扮演著至關重要的角色。不論你是新手還是有一些經驗的小伙伴&#xff0c;本篇文章都會為你詳細介紹接口測試的基本概念、常用測試工具和實際操作技巧&#xff0c;讓你輕松掌握這一技能。 接口測試…

Java數字化智慧工地管理云平臺源碼(人工智能、物聯網、大數據)

智慧工地優勢&#xff1a;"智慧工地”將施工企業現場視頻管理、建筑起重機械安全監控、現場從業人員管理、物料管理、進度管理、揚塵噪聲監測等現場設備有機、高效、科學、規范的結合起來真正實現工程項目業務流與現場各類監控源數據流的有效結合與深度配合&#xff0c;實…

在Hive/Spark上運行執行TPC-DS基準測試 (ORC和TEXT格式)

目前,在Hive/Spark上運行TPC-DS Benchmark主要是通過早期由Hortonworks維護的一個項目:hive-testbench 來完成的。本文我們以該項目為基礎介紹一下具體的操作步驟。不過,該項目僅支持生成ORC和TEXT格式的數據,如果需要Parquet格式,請參考此文《在Hive/Spark上執行TPC-DS基…

動態代理有幾種方式,可以借助Mybatis-plus里面的檢驗動態類

動態代理有很多的分類&#xff1b; 1、JDK原生的動態代理&#xff1b; 2、Spring實現的基于cglib里面的工廠實例化對象&#xff1b; 3、基于原生的cglib造出來的對象 4、基于字節碼的反編譯&#xff1a;assistant 具體的實現類參考&#xff1a; public final class ClassU…

【JVM】對String::intern()方法深入詳解(JDK7及以上)

文章目錄 1、什么是intern&#xff1f;2、經典例題解釋例1例2例3 1、什么是intern&#xff1f; String::intern()是一個本地方法&#xff0c;它的作用是如果字符串常量池中已經包含一個等于此String對象的字符串&#xff0c;則返回代表池中這個字符串的String對象的引用&#…

Java開源項目mall學習筆記(1)——項目初始化

一、學習聲明與項目介紹 該筆記是記錄學習開源項目mall過程的文檔筆記&#xff0c;完全原創&#xff0c;轉載請聲明。同時也對開源項目的作者表示感謝&#xff01; mall: &#x1f525; mall項目是一套基于 SpringBoot Vue uni-app 實現的電商系統&#xff0c;包括前臺商城項…

編譯鴻蒙codelabs安裝時報錯

學習鴻蒙ArkTS時編譯codelabs樣例代碼&#xff0c;發現編譯完成報錯。目前鴻蒙的資料比較少&#xff0c;且官方文檔路徑很深&#xff0c;遂記錄下來&#xff0c;以資來者。 error: failed to start ability. Error while Launching activity修改module.json5中的exported為tru…

ArcGIS 利用cartogram插件制作變形地圖

成果圖 注&#xff1a;本圖數據并不完全對&#xff0c;只做為測試用例 操作 首先需要下載一個插件cartogram 下載地址在這里 https://www.arcgis.com/home/item.html?idd348614c97264ae19b0311019a5f2276 下載完畢之后解壓將Cartograms\HelpFiles下的所有文件復制到ArcGIS…

ffmpeg的使用

1、ffmpeg的安裝 # 安裝wget yum -y install wget # 安裝ffmpeg壓縮包 wget --no-check-certificate https://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.0.3-64bit-static.tar.xz # 解壓 tar -xJf ffmpeg-4.0.3-64bit-static.tar.xz # 進入目錄 cd ffmpeg-4.0.3-64…

【Git】(二)分支

1、創建分支 已存在主分支master&#xff0c;現在需要創建v1.0的版本&#xff0c;一般直接在web頁面操作。 v1.0分支&#xff0c;基線master&#xff0c;稱為項目分支。 假如&#xff0c;v1.0項目存在兩個項目成員sunriver2000和snow&#xff0c;一般還會再針對個人創建個人…

nodejs+vue+elementui學生檔案信息管理系統_06bg9

利用計算機網絡的便利&#xff0c;開發一套基于nodejs的大學生信息管理系統&#xff0c;將會給人們的生活帶來更多的便利&#xff0c;而且在經濟效益上&#xff0c;也會有很大的便利!這可以節省大量的時間和金錢。學生信息管理系統是學校不可缺少的一個環節&#xff0c;其內容直…

說一下什么是tcp的2MSL,為什么客戶端在 TIME-WAIT 狀態必須等待 2MSL 的時間?

1.TCP之2MSL 1.1 MSL MSL:Maximum Segment Lifetime報文段最大生存時間&#xff0c;它是任何報文段被丟棄前在網絡內的最長時間 1.2為什么存在MSL TCP報文段以IP數據報在網絡內傳輸&#xff0c;而IP數據報則有限制其生存時間的TTL字段&#xff0c;并且TTL的限制是基于跳數 1.3…

[高光譜]PyTorch使用CNN對高光譜圖像進行分類

項目原地址&#xff1a; Hyperspectral-Classificationhttps://github.com/eecn/Hyperspectral-ClassificationDataLoader講解&#xff1a; [高光譜]使用PyTorch的dataloader加載高光譜數據https://blog.csdn.net/weixin_37878740/article/details/130929358 一、模型加載 在…

使用JMeter創建數據庫測試

好吧&#xff01;我一直覺得我不聰明&#xff0c;所以&#xff0c;我用最詳細&#xff0c;最明了的方式來書寫這個文章。我相信&#xff0c;我能明白的&#xff0c;你們一定能明白。 我的環境&#xff1a;MySQL&#xff1a;mysql-essential-5.1.51-win32 jdbc驅動&#xff1a;…

mysql 03.查詢(重點)

先準備測試數據&#xff0c;代碼如下&#xff1a; -- 創建數據庫 DROP DATABASE IF EXISTS mydb; CREATE DATABASE mydb; USE mydb;-- 創建student表 CREATE TABLE student (sid CHAR(6),sname VARCHAR(50),age INT,gender VARCHAR(50) DEFAULT male );-- 向student表插入數據…

PHP 公交公司充電樁管理系統mysql數據庫web結構apache計算機軟件工程網頁wamp

一、源碼特點 PHP 公交公司充電樁管理系統是一套完善的web設計系統&#xff0c;對理解php編程開發語言有幫助&#xff0c;系統具有完整的源代碼和數據庫&#xff0c;系統主要采用B/S模式開發。 源碼下載 https://download.csdn.net/download/qq_41221322/88220946 論文下…

【面試問題】當前系統查詢接口需要去另外2個系統庫中實時查詢返回結果拼接優化思路

文章目錄 場景描述優化思路分享資源 場景描述 接口需要從系統1查詢數據&#xff0c;查出的每條數據需要從另一個系統2中再去查詢某些字段&#xff0c; 比如&#xff1a;從系統1中查出100條數據&#xff0c;每條數據需要去系統2中再去查詢出行數據&#xff0c;可能系統1一條數…

socks5 保障網絡安全與爬蟲需求的完美融合

Socks5代理&#xff1a;跨足網絡安全和爬蟲領域的全能選手 Socks5代理作為一種通用的網絡協議&#xff0c;為多種應用場景提供了強大的代理能力。它不僅支持TCP和UDP的數據傳輸&#xff0c;還具備更高級的安全特性&#xff0c;如用戶身份驗證和加密通信。在網絡安全中&#xf…