当前位置: 首页 > news >正文

【原创】为MybatisPlus增加一个逻辑删除插件,让XML中的SQL也能自动增加逻辑删除功能

前言

看到这个标题有人就要说了,D哥啊,MybatisPlus不是本来就有逻辑删除的配置吗,比如@TableLogic注解,配置文件里也能添加如下配置设置逻辑删除。

mybatis-plus:mapper-locations: classpath*:mapper/*.xmlconfiguration:mapUnderscoreToCamelCase: trueglobal-config:db-config:logic-delete-field: dellogic-delete-value: 1logic-notDelete-value: 0

但是我想说,xml中添加了逻辑删除了吗?很明显这个没有,MybatisPlus只在QueryWrapper中做了手脚,而xml是Mybatis的功能,非MybatisPlus的功能。而xml中写SQL又是我工作中最常用到的,优势在于SQL可读性强,结合MybatisX插件并在IDEA中连接database后能够直接跳转到方法和表,且对多表join和子查询支持都比QueryWrapper来得好。而逻辑删除又是会经常漏掉的字段,虽然说手动添加也不费多少时间,但是麻烦的是容易漏掉,特别是子查询和join的情况,而且时间积少成多,我觉得有必要解决这个问题。

本插件适用于绝大部分表都拥有逻辑删除字段的情况!!

本文使用的MybatisPlus的版本为3.5.3.1

不多说了,直接上代码!


/*** @author DCT* @version 1.0* @date 2023/11/9 23:10:18* @description*/
@Slf4j
public class DeleteMpInterceptor implements InnerInterceptor {public static final String LOGIC_DELETE = "LOGIC_DELETE";public static final List<String> excludeFunctions = new ArrayList<>();protected String deleteFieldName;public DeleteMpInterceptor(String deleteFieldName) {this.deleteFieldName = deleteFieldName;}static {excludeFunctions.add("selectList");excludeFunctions.add("selectById");excludeFunctions.add("selectBatchIds");excludeFunctions.add("selectByMap");excludeFunctions.add("selectOne");excludeFunctions.add("selectCount");excludeFunctions.add("selectObjs");excludeFunctions.add("selectPage");excludeFunctions.add("selectMapsPage");}@SneakyThrows@Overridepublic void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {if (InterceptorIgnoreHelper.willIgnoreOthersByKey(ms.getId(), LOGIC_DELETE)) {return;}if (StringUtils.isBlank(deleteFieldName)) {// INFO: Zhouwx: 2023/11/20 没有设置逻辑删除的字段名,也忽略添加逻辑删除return;}PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);String sql = mpBs.sql();Statement statement = CCJSqlParserUtil.parse(sql);if (!(statement instanceof Select)) {return;}String id = ms.getId();int lastIndexOf = id.lastIndexOf(".");String functionName = id.substring(lastIndexOf + 1);if (excludeFunctions.contains(functionName)) {// INFO: DCT: 2023/11/12 QueryWrapper的查询,本来就会加逻辑删除,不需要再加了return;}Select select = (Select) statement;SelectBody selectBody = select.getSelectBody();// INFO: DCT: 2023/11/12 处理核心业务handleSelectBody(selectBody);// INFO: DCT: 2023/11/12 将处理完的数据重新转为MPBoundSqlString sqlChange = statement.toString();mpBs.sql(sqlChange);}protected void handleSelectBody(SelectBody selectBody) {if (selectBody instanceof PlainSelect) {PlainSelect plainSelect = (PlainSelect) selectBody;// INFO: DCT: 2023/11/12 处理join中的内容handleJoins(plainSelect);Expression where = plainSelect.getWhere();FromItem fromItem = plainSelect.getFromItem();EqualsTo equalsTo = getEqualTo(fromItem);if (where == null) {// INFO: DCT: 2023/11/12 where条件为空,增加一个where,且赋值为 表名.del = 0plainSelect.setWhere(equalsTo);} else {// INFO: DCT: 2023/11/12 普通where,后面直接加上本表的 表名.del = 0 AndExpression andExpression = new AndExpression(where, equalsTo);plainSelect.setWhere(andExpression);// INFO: DCT: 2023/11/12 有子查询的处理子查询 handleWhereSubSelect(where);}}}/*** 这一段来自MybatisPlus的租户插件源码,通过递归的方式加上需要的SQL** @param where*/protected void handleWhereSubSelect(Expression where) {if (where == null) {return;}if (where instanceof FromItem) {processOtherFromItem((FromItem) where);return;}if (where.toString().indexOf("SELECT") > 0) {// 有子查询if (where instanceof BinaryExpression) {// 比较符号 , and , or , 等等BinaryExpression expression = (BinaryExpression) where;handleWhereSubSelect(expression.getLeftExpression());handleWhereSubSelect(expression.getRightExpression());} else if (where instanceof InExpression) {// inInExpression expression = (InExpression) where;Expression inExpression = expression.getRightExpression();if (inExpression instanceof SubSelect) {handleSelectBody(((SubSelect) inExpression).getSelectBody());}} else if (where instanceof ExistsExpression) {// existsExistsExpression expression = (ExistsExpression) where;handleWhereSubSelect(expression.getRightExpression());} else if (where instanceof NotExpression) {// not existsNotExpression expression = (NotExpression) where;handleWhereSubSelect(expression.getExpression());} else if (where instanceof Parenthesis) {Parenthesis expression = (Parenthesis) where;handleWhereSubSelect(expression.getExpression());}}}/*** 处理子查询等*/protected void processOtherFromItem(FromItem fromItem) {// 去除括号while (fromItem instanceof ParenthesisFromItem) {fromItem = ((ParenthesisFromItem) fromItem).getFromItem();}if (fromItem instanceof SubSelect) {SubSelect subSelect = (SubSelect) fromItem;if (subSelect.getSelectBody() != null) {// INFO: Zhouwx: 2023/11/20 递归从select开始查找handleSelectBody(subSelect.getSelectBody());}} else if (fromItem instanceof ValuesList) {log.debug("Perform a subQuery, if you do not give us feedback");} else if (fromItem instanceof LateralSubSelect) {LateralSubSelect lateralSubSelect = (LateralSubSelect) fromItem;if (lateralSubSelect.getSubSelect() != null) {SubSelect subSelect = lateralSubSelect.getSubSelect();if (subSelect.getSelectBody() != null) {// INFO: Zhouwx: 2023/11/20 递归从select开始查找handleSelectBody(subSelect.getSelectBody());}}}}protected void handleJoins(PlainSelect plainSelect) {List<Join> joins = plainSelect.getJoins();if (joins == null) {return;}for (Join join : joins) {// INFO: DCT: 2023/11/12 获取表别名,并获取 表.del = 0FromItem rightItem = join.getRightItem();EqualsTo equalsTo = getEqualTo(rightItem);// INFO: DCT: 2023/11/12 获取on右边的表达式Expression onExpression = join.getOnExpression();// INFO: DCT: 2023/11/12 给表达式增加 and 表.del = 0AndExpression andExpression = new AndExpression(onExpression, equalsTo);ArrayList<Expression> expressions = new ArrayList<>();expressions.add(andExpression);// INFO: DCT: 2023/11/12 目前的这个表达式就是and后的表达式了,不用再增加原来的表达式,因为这个and表达式已经包含了原表达式所有的内容了join.setOnExpressions(expressions);}}protected EqualsTo getEqualTo(FromItem fromItem) {Alias alias = fromItem.getAlias();String aliasName = "";if (alias == null) {if (fromItem instanceof Table) {Table table = (Table) fromItem;aliasName = table.getName();}} else {aliasName = alias.getName();}EqualsTo equalsTo = new EqualsTo();Column leftColumn = new Column();leftColumn.setColumnName(aliasName + "." + deleteFieldName);equalsTo.setLeftExpression(leftColumn);equalsTo.setRightExpression(new LongValue(0));return equalsTo;}
}

代码说明

这代码中已经有很多注释了,其实整段代码并非100%我的原创,而是借鉴了MybatisPlus自己的TenantLineInnerIntercept,因为两者的功能实际上非常详尽,我依葫芦画瓢造了一个,特别是中间的handleWhereSubSelect方法,令人拍案叫绝!使用大量递归,通过非常精简的代码处理完了SQL查询中所有的子查询。

getEqualTo方法可以算是逻辑删除插件的核心代码了,先判断表是否存在别名,如果有,就拿别名,如果没有就拿表名,防止出现多个表都有逻辑删除字段的情况下指代不清的情况,出现查询ambiguous错误。通过net.sf.jsqlparser中的EqualsTo表达式,拼上字段名和未被逻辑删除的值0(这里可以按照自己的情况进行修改!)

顶上的excludeFunctions是为了排除QueryWrapper的影响,因为QueryWrapper自己会加上逻辑删除,而这个插件还会再添加一个逻辑删除,导致出现重复,打印出来的SQL不美观。

使用方法

和MybatisPlus其他的插件一样,都通过@Bean的方式进行配置

    @Value("${mybatis-plus.global-config.db-config.logic-delete-field}")private String deleteFieldName;@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new DeleteMpInterceptor(deleteFieldName));return interceptor;}

我这里的deleteFieldName直接借用了MybatisPlus自己的逻辑删除配置,可以自己设置

排除使用这个插件

如果有几张表是没有逻辑删除字段的,那么这个插件自动补的逻辑删除字段则会导致SQL出现报错,可以通过添加以下注解@InterceptorIgnore排除插件对于该方法的生效

@Repository
interface ExampleMapper : BaseMapper<ExampleEntity> {@InterceptorIgnore(others = [DeleteMpInterceptor.LOGIC_DELETE + "@true"])fun findByList(query: ExampleQo): List<ExampleListVo>
}

上面的代码是Kotlin写的,但是不妨碍查看

运行效果

mapper中代码为:

/*** @author DCTANT* @version 1.0* @date 2023/11/20 17:40:41* @description*/
@Repository
interface ExampleMapper : BaseMapper<ExampleEntity> {fun findByList(query: ExampleQo): List<ExampleListVo>
}

xml中的代码为:

    <select id="findByList" resultType="com.itdct.server.admin.example.vo.ExampleListVo">select t.* from test_example as t<where><if test="name != null and name != ''">and t.name = #{name}</if><if test="number != null">and t.number = #{number}</if><if test="keyword != null and keyword != ''">and t.name like concat('%',#{keyword},'%')</if><if test="startTime != null">and t.create_time &gt; #{startTime}</if><if test="endTime != null">and t.create_time &lt; #{endTime}</if></where>order by t.create_time desc</select>

执行效果为:

t.del = 0就是逻辑删除插件添加的代码,当然join和子查询我也使用了,目前来看没有什么问题

欢迎大家提出修改意见

目前这个代码还处于Demo阶段,并没有上线使用,还是处于没充分测试的状态,欢迎大家提出整改意见!如果有bug我也会及时修复。

相关文章:

【原创】为MybatisPlus增加一个逻辑删除插件,让XML中的SQL也能自动增加逻辑删除功能

前言 看到这个标题有人就要说了&#xff0c;D哥啊&#xff0c;MybatisPlus不是本来就有逻辑删除的配置吗&#xff0c;比如TableLogic注解&#xff0c;配置文件里也能添加如下配置设置逻辑删除。 mybatis-plus:mapper-locations: classpath*:mapper/*.xmlconfiguration:mapUnd…...

ABAP 长文本操作

关联表 1.STXH&#xff1a;长文本抬头表 2.STXL&#xff1a;长文本行表 3.TTXID&#xff1a;Text ID 表 4.TTXOB&#xff1a;Textobject表 5.订单中众多的文本描述&#xff0c;我们怎么知道其对应的【对象】&【ID】呢&#xff1f; 可SE38-通过查找程式&#xff1a;RST…...

C++:哈希表的模拟实现

文章目录 哈希哈希冲突哈希函数 解决哈希冲突闭散列&#xff1a;开散列 哈希 在顺序结构和平衡树中&#xff0c;元素的Key和存储位置之间没有必然的联系&#xff0c;在进行查找的时候&#xff0c;要不断的进行比较&#xff0c;时间复杂度是O(N)或O(logN) 而有没有这样一种方案…...

echarts实现如下图功能代码

这里写自定义目录标题 const option {tooltip: {trigger: axis},legend: {left: "-1px",top:15px,type: "scroll",icon:rect,data: [{name:1, textStyle:{color: theme?"#E5EAF3":#303133,fontSize:14}}, {name: 2, textStyle:{color: theme…...

Java 开源重试类 guava-retrying 使用案例

使用背景 需要重复尝试执行某些动作&#xff0c;guava-retrying 提供了成型的重试框架 依赖 <dependency><groupId>com.github.rholder</groupId><artifactId>guava-retrying</artifactId><version>${retrying.version}</version>…...

服务器 jupyter 文件名乱码问题

对于本台电脑&#xff0c;autodl服务器&#xff0c;上传中文文件时&#xff0c;从压缩包名到压缩包里的文件名先后会出现中文乱码的问题。 Xftp 首先是通过Xftp传输压缩包到Autodl服务器&#xff1a; 1、打开Xftp&#xff0c;进入软件主界面&#xff0c;点击右上角【文件】菜…...

Ubuntu设设置默认外放和麦克风设备

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、pulseaudio 是什么&#xff1f;二、配置外放1.查看所有的外放设备2.设定默认的外放设备3.设定外放设备的声音强度4.设定外放设备静音 三、配置麦克风1.查看…...

【教程】Sqlite迁移到mysql(django)

1、先将sqlite db文件导出sql sqlite3 db.sqlite3 .dump>output.sql db.sqlite3 是 sqlite 数据库文件 output.sql是导出sql文件的名称 2、sql文件转换、处理 sed s/AUTOINCREMENT/AUTO_INCREMENT/g output.sql | sed s/datetime/timestamp/g | sed s/INTEGER/int/g &g…...

【漏洞复现】DPTech VPN存在任意文件读取漏洞

漏洞描述 DPtech是在网络、安全及应用交付领域集研发、生产、销售于一体的高科技企业。DPtech VPN智能安全网关是迪普科技面向广域互联应用场景推出的专业安全网关产品&#xff0c;集成了IPSec、SSL、L2TP、GRE等多种VPN技术&#xff0c;支持国密算法&#xff0c;实现分支机构…...

CentOS 8搭建WordPress

步骤 1: 更新系统 确保你的系统是最新的&#xff0c;使用以下命令更新&#xff1a; bashCopy code sudo dnf update 步骤 2: 安装Apache bashCopy code sudo dnf install httpd 启动Apache&#xff0c;并设置开机自启动&#xff1a; bashCopy code sudo systemctl star…...

服务器安全防护导致使用多款行业顶尖软件搭配使用,还是单独一款解决呢?

如今&#xff0c;在全球各地&#xff0c;数以千计的公司、组织和个人都依赖于服务器来存储和访问重要数据&#xff0c;托管应用程序&#xff0c;以及提供服务。但是&#xff0c;这些服务器不断面临着来自网络黑客的威胁&#xff0c;因此服务器的安全成为了当务之急。 在这种情…...

【Spring篇】Spring注解式开发

本文根据哔哩哔哩课程内容结合自己自学所得&#xff0c;用于自己复习&#xff0c;如有错误欢迎指正&#xff1b; 我在想用一句话激励我自己努力学习&#xff0c;却想不出来什么惊为天人、精妙绝伦的句子&#xff0c;脑子里全是上课老师想说却没想起的四个字 “ 唯手熟尔 ”&am…...

14.(vue3.x+vite)组件间通信方式之pinia

前端技术社区总目录(订阅之前请先查看该博客) 示例效果 Pinia简介 Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 Pinia与Vuex比较 (1)Vue2和Vue3都支持,这让我们同时使用Vue2和Vue3的小伙伴都能很快上手。 (2)pinia中只有state、getter、action,抛弃了Vu…...

DolphinDB 浙商银行 | 第二期现场培训圆满结束

自 DolphinDB 高级工程师计划开展以来&#xff0c;客户们纷纷响应&#xff0c;除了定期收看我们每周三开设的线上公开课外&#xff0c;也有部分客户报名参加了 “总部工程师培训计划” 。 上周&#xff0c;我们迎来了总部培训的第二期学员&#xff1a;来自浙商银行的4位策略研…...

DBS note4:Buffer Management

目录 1、介绍 2、缓冲池 3、处理页面请求 4、LRU替换和时钟策略 1&#xff09;顺序扫描性能 - LRU 5、最近最常使用替换策略&#xff08;MRU Replacement&#xff09; 1&#xff09;Sequential Scanning Performance - MRU 6、练习题 1&#xff09;判断真假 2&#xf…...

Linux 中 .tar 和 tar.gz 的区别

1、前言 有时候你会发现&#xff0c;即便是有些拥有 3 年左右工作经验的运维或开发工程师对 .tar 和 .tar.gz 的区别并不是很清楚。.tar 和 .tar.gz 是在 Linux 系统中用于打包和压缩文件的两种常见格式。它们之间的主要区别在于压缩算法和文件扩展名。 2、区别 .tar .tar 是…...

区域人员超限AI算法的介绍及TSINGSEE视频智能分析技术的行业应用

视频AI智能分析已经渗透到人类生活及社会发展的各个方面。从生活中的人脸识别、停车场的车牌识别、工厂园区的翻越围栏识别、入侵识别、工地的安全帽识别、车间流水线产品的品质缺陷AI检测等&#xff0c;AI智能分析技术无处不在。在某些场景中&#xff0c;重点区域的人数统计与…...

asp.net mvc点餐系统餐厅管理系统

1. 主要功能 ① 管理员、收银员、厨师的登录 ② 管理员查看、添加、删除菜品类型 ③ 管理员查看、添加、删除菜品&#xff0c;对菜品信息进行简介和封面的修改 ④ 收银员浏览、搜索菜品&#xff0c;加入购物车后进行结算&#xff0c;生成订单 ⑤ 厨师查看待完成菜品信息…...

SpringBoot 使用多SqlSessionFactory下的事务问题

如下配置了两个数据源&#xff1a; spring:datasource:ds1:jdbc-url: jdbc:mysql://localhost:3307/spring-boot-demos?serverTimezoneUTC&useUnicodetrue&characterEncodingutf8&useSSLfalse&allowPublicKeyRetrievaltrueusername: rootpassword: passwordd…...

浏览器内置NoSQL数据库IndexedDB

IndexedDB - 浏览器内容数据库 indexedDB 是一种浏览器内置的NoSQL数据库&#xff0c;它使用键值对存储数据&#xff0c;用于在客户端存储大量结构化数据。它支持离线应用程序和高效的数据检索&#xff0c;可以在 Web 应用程序中替代传统的 cookie 和 localStorage。 IndexDB是…...

浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)

✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义&#xff08;Task Definition&…...

Ubuntu系统下交叉编译openssl

一、参考资料 OpenSSL&&libcurl库的交叉编译 - hesetone - 博客园 二、准备工作 1. 编译环境 宿主机&#xff1a;Ubuntu 20.04.6 LTSHost&#xff1a;ARM32位交叉编译器&#xff1a;arm-linux-gnueabihf-gcc-11.1.0 2. 设置交叉编译工具链 在交叉编译之前&#x…...

三维GIS开发cesium智慧地铁教程(5)Cesium相机控制

一、环境搭建 <script src"../cesium1.99/Build/Cesium/Cesium.js"></script> <link rel"stylesheet" href"../cesium1.99/Build/Cesium/Widgets/widgets.css"> 关键配置点&#xff1a; 路径验证&#xff1a;确保相对路径.…...

Vue2 第一节_Vue2上手_插值表达式{{}}_访问数据和修改数据_Vue开发者工具

文章目录 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染2. 插值表达式{{}}3. 访问数据和修改数据4. vue响应式5. Vue开发者工具--方便调试 1.Vue2上手-如何创建一个Vue实例,进行初始化渲染 准备容器引包创建Vue实例 new Vue()指定配置项 ->渲染数据 准备一个容器,例如: …...

屋顶变身“发电站” ,中天合创屋面分布式光伏发电项目顺利并网!

5月28日&#xff0c;中天合创屋面分布式光伏发电项目顺利并网发电&#xff0c;该项目位于内蒙古自治区鄂尔多斯市乌审旗&#xff0c;项目利用中天合创聚乙烯、聚丙烯仓库屋面作为场地建设光伏电站&#xff0c;总装机容量为9.96MWp。 项目投运后&#xff0c;每年可节约标煤3670…...

【git】把本地更改提交远程新分支feature_g

创建并切换新分支 git checkout -b feature_g 添加并提交更改 git add . git commit -m “实现图片上传功能” 推送到远程 git push -u origin feature_g...

DeepSeek 技术赋能无人农场协同作业:用 AI 重构农田管理 “神经网”

目录 一、引言二、DeepSeek 技术大揭秘2.1 核心架构解析2.2 关键技术剖析 三、智能农业无人农场协同作业现状3.1 发展现状概述3.2 协同作业模式介绍 四、DeepSeek 的 “农场奇妙游”4.1 数据处理与分析4.2 作物生长监测与预测4.3 病虫害防治4.4 农机协同作业调度 五、实际案例大…...

使用 Streamlit 构建支持主流大模型与 Ollama 的轻量级统一平台

🎯 使用 Streamlit 构建支持主流大模型与 Ollama 的轻量级统一平台 📌 项目背景 随着大语言模型(LLM)的广泛应用,开发者常面临多个挑战: 各大模型(OpenAI、Claude、Gemini、Ollama)接口风格不统一;缺乏一个统一平台进行模型调用与测试;本地模型 Ollama 的集成与前…...

rnn判断string中第一次出现a的下标

# coding:utf8 import torch import torch.nn as nn import numpy as np import random import json""" 基于pytorch的网络编写 实现一个RNN网络完成多分类任务 判断字符 a 第一次出现在字符串中的位置 """class TorchModel(nn.Module):def __in…...

python报错No module named ‘tensorflow.keras‘

是由于不同版本的tensorflow下的keras所在的路径不同&#xff0c;结合所安装的tensorflow的目录结构修改from语句即可。 原语句&#xff1a; from tensorflow.keras.layers import Conv1D, MaxPooling1D, LSTM, Dense 修改后&#xff1a; from tensorflow.python.keras.lay…...