@intercepts拦截更新语句实现create_time,update_time自动注入

文章介绍了如何使用Java编程中的Interceptor接口和SpringReflectionUtils库,实现在更新操作时自动填充POJO对象的创建用户、时间、版本号等常见字段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开箱即用

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Component
public class SaveAndUpdateInteceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        Object parameter = args[1];
        if (parameter instanceof Map) {
            ((Map<?, ?>) parameter).values().forEach(PojoUtil::setCommonField);
        } else {
            PojoUtil.setCommonField(parameter);
        }
        return invocation.proceed();
    }
}

public class PojoUtil {
    static Logger logger = LoggerFactory.getLogger(PojoUtil.class);

    public static <T> void setCommonField(T t, String userId) {
        Object id = SpringReflectionUtils.getField("id", t);

        if (Objects.isNull(id) || StringUtils.isEmpty(id.toString())) {
            SpringReflectionUtils.setField("createUserId", t, userId);
            SpringReflectionUtils.setField("createTime", t, new Date());
            try {
                SpringReflectionUtils.setField("rev", t, 1);
            } catch (Exception e) {
                //ignore
            }
        }
        SpringReflectionUtils.setField("updateTime", t, new Date());
        SpringReflectionUtils.setField("updateUserId", t, userId);
        SpringReflectionUtils.setField("deleteFlag", t, "0");
    }

    public static <T> void setCommonField(T t) {
        setCommonField(t, "1");
    }
}

public class SpringReflectionUtils {
    private static final Logger logger = LoggerFactory.getLogger(SpringReflectionUtils.class);

    /**
     * Set the field represented by the supplied {@linkplain Field field object} on
     * the specified {@linkplain Object target object} to the specified {@code value}.
     * <p>In accordance with {@link Field#set(Object, Object)} semantics, the new value
     * is automatically unwrapped if the underlying field has a primitive type.
     * <p>This method does not support setting {@code static final} fields.
     * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}.
     *
     * @param fieldName the field to set
     * @param target    the target object on which to set the field
     *                  (or {@code null} for a static field)
     * @param value     the value to set (may be {@code null})
     */![在这里插入图片描述](https://img-blog.csdnimg.cn/350856429ff04344b5744b463bec27b2.jpeg#pic_center)

    public static void setField(String fieldName, Object target, Object value) {
        Field field = ReflectionUtils.findField(target.getClass(), fieldName);
        Assert.notNull(target,"对象不能为空");
        if (field == null) {
            logger.warn("未找到类[{}]的[{}]字段", target.getClass(), fieldName);
            return;
        }
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, target, value);
    }


    /**
     * Get the field represented by the supplied {@link Field field object} on the
     * specified {@link Object target object}. In accordance with {@link Field#get(Object)}
     * semantics, the returned value is automatically wrapped if the underlying field
     * has a primitive type.
     * <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}.
     * @param field the field to get
     * @param target the target object from which to get the field
     * (or {@code null} for a static field)
     * @return the field's current value
     */
    @Nullable
    public static Object getField(String fieldName, Object target) {
        Field field = ReflectionUtils.findField(target.getClass(), fieldName);
        if (field == null){return null;}
        ReflectionUtils.makeAccessible(field);
        return ReflectionUtils.getField(field, target);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值