欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis plus 创建时间创建人,修改时间修改人通用插件

程序员文章站 2022-04-01 18:50:52
package com.itl.iap.common.base.interceptor;import com.itl.iap.common.base.dto.UserTDto;import com.itl.iap.common.base.utils.UserUtil;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.binding.MapperMethod;import org.apache.ibatis.executor.Exe...
package com.itl.iap.common.base.interceptor;

import com.itl.iap.common.base.dto.UserTDto;
import com.itl.iap.common.base.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @author 不会游泳的鱼
 * @version 1.0
 * @date 2020/7/28 15:51
 */
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Slf4j
@SuppressWarnings("all")
public class SqlInterceptor implements Interceptor {
    /**
     * 创建时间
     */
    private static final String CREATE_TIME = "createDate";
    private static final String CREATER = "creater";
    /**
     * 更新时间
     */
    private static final String UPDATE_TIME = "lastUpdateDate";
    private static final String UPDATE_BY = "lastUpdateBy";
    @Autowired
    private UserUtil userUtil;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return invokeUpdate(invocation);
    }

    // 修改操作
    private Object invokeUpdate(Invocation invocation) throws Exception {
        // 获取第一个参数
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        // 获取参数
        Object args = invocation.getArgs()[1];
        // 判断参数类型  是不是MapperMethod.ParamMap 是 就循环更改  不是就是对象直接更改 
        if (args instanceof MapperMethod.ParamMap) {
            MapperMethod.ParamMap<Object> mapObj = (MapperMethod.ParamMap<Object>) invocation.getArgs()[1];
            for (Map.Entry<String, Object> obj : mapObj.entrySet()) {
                Object paramObj = mapObj.get(obj.getKey());
                Field[] fields = paramObj.getClass().getDeclaredFields();
                if (paramObj == null || fields == null) {
                    return invocation.proceed();
                }
                // 如果 insert 语句  则添加创建时间创建人 修改时间和修改人
                if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
                    this.setAllParams(fields, paramObj, CREATE_TIME, new Date());
                    this.setAllParams(fields, paramObj, CREATER, UPDATE_BY.toString());
                    this.setAllParams(fields, paramObj, UPDATE_BY, UPDATE_BY.toString());
                    this.setAllParams(fields, paramObj, UPDATE_TIME, new Date());
                    // 如果是update语句  则添加修改时间修改人
                } else if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
                    this.setAllParams(fields, paramObj, UPDATE_BY, UPDATE_BY.toString());
                    this.setAllParams(fields, paramObj, UPDATE_TIME, new Date());
                }
            }
        } else {
            Field[] fields = args.getClass().getDeclaredFields();
            if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
                this.setAllParams(fields, args, CREATE_TIME, new Date());
                this.setAllParams(fields, args, CREATER, UPDATE_BY.toString());
                this.setAllParams(fields, args, UPDATE_BY, UPDATE_BY.toString());
                this.setAllParams(fields, args, UPDATE_TIME, new Date());
                // 如果是update预计  则添加修改时间修改人
            } else if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
                this.setAllParams(fields, args, UPDATE_BY, UPDATE_BY.toString());
                this.setAllParams(fields, args, UPDATE_TIME, new Date());
            }
        }
        return invocation.proceed();
    }

    /**
     *  根据传递参数放进行修改
     * @param fields 反射存在的参数
     * @param obj 需要改变的对象
     * @param valueKey 变更的字段
     * @param valObj 变更参数类型
     */
    private void setAllParams(Field[] fields, Object obj, String valueKey, Object valObj) {
        UserTDto user = this.getUser();
        if (user != null && user.getUserName() != null) {
            for (int i = 0; i < fields.length; i++) {
                if (valueKey.toLowerCase().equals(fields[i].getName().toLowerCase())) {
                    try {
                        if (valObj instanceof Date) {
                            fields[i].setAccessible(true);
                            fields[i].set(obj, new Date());
                            fields[i].setAccessible(false);
                        }
                        if (valObj instanceof String) {
                            fields[i].setAccessible(true);
                            fields[i].set(obj, user.getUserName());
                            fields[i].setAccessible(false);
                        }
                        break;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // 获取用户 这是一个工具类
    private UserTDto getUser() {
        return userUtil.getUser();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    @Override
    public void setProperties(Properties properties) {

    }


}

本文地址:https://blog.csdn.net/qq_14902731/article/details/107669468