mybatis-plus填充updateBy、updateTime等字段

/**
* 自定义的 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追踪到。 

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis-Plus提供了公共字段填充的功能,可以在插入和更新操作时自动填充公共字段,减少代码重复和出错的可能性。下面是Java代码实现公共字段填充的示例: 1. 创建公共字段填充器类 ```java @Component public class MyMetaObjectHandler implements MetaObjectHandler { // 插入时填充字段 private static final String CREATE_TIME = "createTime"; private static final String UPDATE_TIME = "updateTime"; private static final String CREATE_BY = "createBy"; private static final String UPDATE_BY = "updateBy"; @Override public void insertFill(MetaObject metaObject) { // 填充创建时间和更新时间 this.strictInsertFill(metaObject, CREATE_TIME, LocalDateTime::now, LocalDateTime.class); this.strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime::now, LocalDateTime.class); // 填充创建人和更新人 this.strictInsertFill(metaObject, CREATE_BY, "system", String.class); this.strictInsertFill(metaObject, UPDATE_BY, "system", String.class); } @Override public void updateFill(MetaObject metaObject) { // 填充更新时间 this.strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime::now, LocalDateTime.class); // 填充更新人 this.strictUpdateFill(metaObject, UPDATE_BY, "system", String.class); } } ``` 2. 配置公共字段填充器 ```java @Configuration public class MybatisPlusConfig { @Autowired private MyMetaObjectHandler metaObjectHandler; @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); // 添加公共字段填充器 List<MetaObjectHandler> metaObjectHandlers = new ArrayList<>(); metaObjectHandlers.add(metaObjectHandler); interceptor.setMetaObjectHandlers(metaObjectHandlers); return interceptor; } } ``` 在以上示例中,我们创建了一个名为MyMetaObjectHandler的公共字段填充器类,实现了MetaObjectHandler接口,并在insertFill和updateFill方法中分别填充了创建时间、更新时间、创建人和更新人等公共字段。然后在MybatisPlusConfig中将MyMetaObjectHandler配置到MybatisPlusInterceptor中,作为公共字段填充器。这样,在执行插入和更新操作时,就会自动填充公共字段,无需手动设置,大大提高了开发效率和数据准确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值