前言
看到这个标题有人就要说了,D哥啊,MybatisPlus不是本来就有逻辑删除的配置吗,比如@TableLogic注解,配置文件里也能添加如下配置设置逻辑删除。
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
configuration:
mapUnderscoreToCamelCase: true
global-config:
db-config:
logic-delete-field: del
logic-delete-value: 1
logic-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
@Override
public 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 将处理完的数据重新转为MPBoundSql
String 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 = 0
plainSelect.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) {
// in
InExpression expression = (InExpression) where;
Expression inExpression = expression.getRightExpression();
if (inExpression instanceof SubSelect) {
handleSelectBody(((SubSelect) inExpression).getSelectBody());
}
} else if (where instanceof ExistsExpression) {
// exists
ExistsExpression expression = (ExistsExpression) where;
handleWhereSubSelect(expression.getRightExpression());
} else if (where instanceof NotExpression) {
// not exists
NotExpression 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 = 0
FromItem rightItem = join.getRightItem();
EqualsTo equalsTo = getEqualTo(rightItem);
// INFO: DCT: 2023/11/12 获取on右边的表达式
Expression onExpression = join.getOnExpression();
// INFO: DCT: 2023/11/12 给表达式增加 and 表.del = 0
AndExpression 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;
@Bean
public 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 > #{startTime}</if>
<if test="endTime != null">and t.create_time < #{endTime}</if>
</where>
order by t.create_time desc
</select>
执行效果为:
t.del = 0就是逻辑删除插件添加的代码,当然join和子查询我也使用了,目前来看没有什么问题
欢迎大家提出修改意见
目前这个代码还处于Demo阶段,并没有上线使用,还是处于没充分测试的状态,欢迎大家提出整改意见!如果有bug我也会及时修复。