mybatis拦截器通过反射自动注入创建用户、创建时间、更新用户及更新时间

该博客介绍了如何在Spring Boot中配置MyBatis拦截器,通过反射自动注入创建人和时间信息。拦截器针对Executor类的update方法,在插入和更新操作时检查并设置用户ID和时间戳,确保数据完整性。

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

1、Configuration加入到mybatis拦截器.

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xxxx
 */
@Configuration
public class MybatisConfiguration {

    @Bean
    public Boolean setAutoFillValueInterceptor(SqlSessionFactory sqlSessionFactory) {
        org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
        configuration.addInterceptor(new MybatisInterceptor());
        return Boolean.TRUE;
    }

}

2.配置拦截器



import com.mt.common.core.domain.model.LoginUser;
import com.mt.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
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.Signature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @Description:mybatis拦截器通过反射自动注入创建人、创建时间、修改人、修改时间
 * @author: xxx
 * @date: 2022年8月17日
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

   /**
     * 获取用户缓存信息
     */
    public LoginUser getLoginUser() {
        try{
            return SecurityUtils.getLoginUser();
        }catch (Exception e){
            return new LoginUser();
        }
    }

@Override
    public Object intercept(Invocation invocation) throws Throwable {
        // TODO Auto-generated method stub
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (parameter == null) {
            return invocation.proceed();
        }
        //sql命令类型为插入,自动注入创建人信息
        if (SqlCommandType.INSERT == sqlCommandType) {
            LoginUser userEntity = getLoginUser();
            if(null == userEntity){
                return null;
            }
Field[] fields = parameter.getClass().getDeclaredFields();
            for (Field field : fields) {
                log.info("------field.name------" + field.getName());
                try {
                    // 注入创建用户id
                    if ("createBy".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createBy = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createBy == null || local_createBy.equals("")) {
                            if (userEntity != null) {
                                // 登录人账号
                                field.setAccessible(true);
                                field.set(parameter, userEntity.getUsername());
                                //field.set("updateBy", userEntity.getUsername());
                                field.setAccessible(false);
                            }
                        }
       
}
                    // 注入创建时间
                    if ("createTime".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createDate = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createDate == null || local_createDate.equals("")) {
                            field.setAccessible(true);
                            field.set(parameter, new Date());
                            //field.set("updateTime", new Date());
                            field.setAccessible(false);
                        }
}
                } catch (Exception e) {
                }
            }
        }
 //sql命令类型为更新,自动注入修改人信息
        if (SqlCommandType.UPDATE == sqlCommandType) {
            LoginUser userEntity = getLoginUser();
            if(null == userEntity){
                return null;
            }
            Field[] fields = parameter.getClass().getDeclaredFields();
            for (Field field : fields) {
                log.info("------field.name------" + field.getName());
                try {
// 注入创建用户id
                    if ("updateBy".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createBy = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createBy == null || local_createBy.equals("")) {
                            if (userEntity != null) {
                                // 登录人账号
                                field.setAccessible(true);
                                field.set(parameter, userEntity.getUsername());
                                field.setAccessible(false);
                            }
                        }
                    }
// 注入创建时间
                    if ("updateTime".equals(field.getName())) {
                        field.setAccessible(true);
                        Object local_createDate = field.get(parameter);
                        field.setAccessible(false);
                        if (local_createDate == null || local_createDate.equals("")) {
                            field.setAccessible(true);
                            field.set(parameter, new Date());
                            field.setAccessible(false);
                        }
                    }
 } catch (Exception e) {
                }
            }
        }
        return invocation.proceed();
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值