/**
* 自定义的 sql 注入
*
* @author L.cm
*/
public class BladeSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
List<AbstractMethod> methodList = new ArrayList<>();
methodList.add(new InsertIgnore());
methodList.add(new Replace());
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
methodList.add(new LogicDeleteByIdWithFill());
methodList.add(new LogicDeleteBatchByIdsWithFill());
methodList.addAll(super.getMethodList(mapperClass, tableInfo));
return Collections.unmodifiableList(methodList);
}
}
/**
* 如果是逻辑删除且标记有填充字段的情况下,填充更新时间和更新人id <br/>
* 用法:
* <pre>
* 使用默认deleteBatchIds方法:
* 注入方法: new LogicDeleteBatchByIdsWithFill()
* </pre>
* <pre>
* 自定义Mapper方法名:
* 注入方法: new LogicDeleteBatchByIdsWithFill("testDeleteBatch")
* 增加Mapper方法: int testDeleteBatch(@Param(Constants.COLLECTION) List<Entity> entityList);
* </pre>
*
* @author Wei
* @create 2022-10-17 19:50
*/
public class LogicDeleteBatchByIdsWithFill extends DeleteBatchByIds {
public LogicDeleteBatchByIdsWithFill() {
super();
}
public LogicDeleteBatchByIdsWithFill(String name) {
super(name);
}
@Override
public String logicDeleteScript(TableInfo tableInfo, SqlMethod sqlMethod) {
final String lastUpdateBy = "last_update_by";
final String lastUpdateTime = "last_update_time";
String funcSignature = "@org.springblade.core.secure.utils.AuthUtil@getUserId()";
List<TableFieldInfo> fieldInfos = tableInfo.getFieldList().stream()
.filter(TableFieldInfo::isWithUpdateFill)
.filter(f -> !f.isLogicDelete())
.collect(toList());
if (CollectionUtils.isNotEmpty(fieldInfos)) {
String sqlScript = fieldInfos.stream().map(i -> {
if (lastUpdateBy.equals(i.getColumn())) {
String setColScript = String.format("%s = ${%s},", lastUpdateBy, funcSignature);
return SqlScriptUtils.convertIf(setColScript, String.format("%s != null and %s > 0", funcSignature, funcSignature), true);
} else if (lastUpdateTime.equals(i.getColumn())) {
return String.format("%s = now(),", lastUpdateTime);
}
return EMPTY;
}).collect(joining(EMPTY));
String sqlSet = "SET " + sqlScript + tableInfo.getLogicDeleteSql(false, false);
return String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlSet, tableInfo.getKeyColumn(),
SqlScriptUtils.convertForeach(
SqlScriptUtils.convertChoose("@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(item.getClass())",
"#{item}", "#{item." + tableInfo.getKeyProperty() + "}"),
COLLECTION, null, "item", COMMA),
tableInfo.getLogicDeleteSql(true, true));
} else {
return super.logicDeleteScript(tableInfo, sqlMethod);
}
}
}
这样写的理由:
mybatis-plus在MappedStatement中sql注册的时候,会通过sql的方法名作为map的key,判断是否存在,存在就不再添加。这样,mybatis-plus就使用了我们自定义的logicDeleteByIds方法。
可以通过启动日志的warn追踪到。