spring Mybatis拦截器,动态修改时间

本文介绍如何使用Spring Mybatis拦截器,在执行修改语句时自动更新记录的修改时间。同样方法也可应用于插入操作,如添加uuid和创建者信息。只需传入一个参数,即可实现两个效果。

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

例子:

执行修改语句时,自动更新修改时间。
(同理可得插入时,添加uuid、创建者)

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;

/**
 * 拦截对象,给对象在增加、修改时添加数据。
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Component
public class OpeInfoInterceptor implements Interceptor {

    public Object intercept(Invocation invocation) throws Throwable {

        //获取参数
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        if (mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE) {
            Object arg1 = args[1];
            //如果使用@Param 来传入参数,args[1] 类型为map
            if(arg1 instanceof Map){
                Map map=(Map) arg1;
                for (Object key : map.keySet()) {
                    //传入参数会重复(不知道为啥),做去重处理,只需修改其中一个参数,都能成功修改对象
                   if(key.toString().contains("param")) {
                       handelUpdateData(map.get(key));
                   }
                }
            }else {
                handelUpdateData(arg1);
            }
        }
        return invocation.proceed();

    }

    private void handelUpdateData(Object obj) throws IllegalAccessException {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
                if (field.getName().equals("gmtModify")) {
                    field.setAccessible(true);
                    field.set(obj, new Date());
            }
        }
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    public void setProperties(Properties properties) {

    }

}

只传入一个参数,结果有2个。
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值