mybatis 攔截器(Interceptor)實現公共屬性賦值(代碼優化)

 https://blog.csdn.net/qq_38428623/article/details/103981432

package com.jh.erp.web.interceptor;

import com.jh.erp.service.model.UserInfo;
import com.jh.erp.service.util.UserInfoUtils;
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 java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

/**
 * @ProductName: IntelliJ IDEA
 * @ProjectName: erp-parent
 * @PackageName: com.jh.erp.web.interceptor
 * @Author: Choj
 * @CreateDateTime: 2020/1/14 20:32
 * @ModifyDateTime:
 * @Name: UserUpdateInterceptor
 * @Description: 用於賦值用戶信息的攔截器
 * Executor
 * StatementHandler
 * ParameterHandler
 * ResultSetHandler
 * @Since: 1.0
 **/
@Intercepts({@Signature(type = Executor.class, method = "update"
        , args = {MappedStatement.class, Object.class})})
public class UserUpdateInterceptor implements Interceptor {

    @Override
    public Object intercept(final Invocation invocation) throws Exception {
        Object obj = null;
        if (invocation.getTarget() instanceof Executor && invocation.getArgs().length == 2) {
            final Executor executor = (Executor) invocation.getTarget();
            // 獲取第一個參數
            final MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
            final Object paramObj = invocation.getArgs()[1];
            if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
                obj = this.executeInsert(executor, ms, paramObj);
            } else if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
                obj = this.executeUpdate(executor, ms, paramObj);
            } else if (ms.getSqlCommandType() == SqlCommandType.DELETE) {
                obj = this.executeDelete(executor, ms, paramObj);
            }
        }
        return obj == null ? invocation.proceed() : obj;
    }

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

    @Override
    public void setProperties(final Properties properties) {

    }

    // ------ 私有方法 --------

    /**
     * 更新操作
     *
     * @param executor executor
     * @param ms       ms
     * @param paramObj 參數
     * @return 返回執行結果
     */
    private Object executeInsert(final Executor executor, final MappedStatement ms, final Object paramObj) throws Exception {
        final Field[] fields = paramObj.getClass().getDeclaredFields();
        for (final Field field : fields) {
            field.setAccessible(true);
            final String fieldName = field.getName();
            if ("id".equalsIgnoreCase(fieldName)) {
                field.set(paramObj, UUID.randomUUID().toString());
                continue;
            }
            final UserInfo userInfo = this.getUserInfo();
            if (userInfo == null) {
                return null;
            }
            switch (fieldName) {
                case "id":
                    field.set(paramObj, UUID.randomUUID().toString());
                    break;
                case "createUserId":
                    field.set(paramObj, userInfo.getId());
                    break;
                case "createUserCode":
                    field.set(paramObj, userInfo.getCode());
                    break;
                case "createUserName":
                    field.set(paramObj, userInfo.getUsername());
                    break;
                default:
                    break;
            }
        }
        return executor.update(ms, paramObj);
    }

    /**
     * 新增操作
     *
     * @param executor executor
     * @param ms       ms
     * @param paramObj 參數
     * @return 返回執行結果
     */
    private Object executeUpdate(final Executor executor, final MappedStatement ms, final Object paramObj) throws Exception {
        if (paramObj instanceof MapperMethod.ParamMap) {
            final MapperMethod.ParamMap paramMap = (MapperMethod.ParamMap) paramObj;
            for (final Object entity : paramMap.entrySet()) {
                final Field[] fields = entity.getClass().getDeclaredFields();
                for (final Field field : fields) {
                    field.setAccessible(true);
                    final String fieldName = field.getName();
                    final UserInfo userInfo = this.getUserInfo();
                    if (userInfo == null) {
                        return null;
                    }
                    switch (fieldName) {
                        case "modifyDate":
                            field.set(paramObj, new Date());
                            break;
                        case "modifyUserId":
                            field.set(paramObj, userInfo.getId());
                            break;
                        case "modifyUserCode":
                            field.set(paramObj, userInfo.getCode());
                            break;
                        case "modifyUserName":
                            field.set(paramObj, userInfo.getUsername());
                            break;
                        default:
                            break;
                    }
                }
            }
        }
        return executor.update(ms, paramObj);
    }

    /**
     * 新增操作
     *
     * @param executor executor
     * @param ms       ms
     * @param paramObj 參數
     * @return 返回執行結果
     */
    private Object executeDelete(final Executor executor, final MappedStatement ms, final Object paramObj) throws Exception {
        final Field[] fields = paramObj.getClass().getDeclaredFields();
        for (final Field field : fields) {
            field.setAccessible(true);
            final String fieldName = field.getName();
            switch (fieldName) {
                case "deleted":
                    field.set(paramObj, true);
                    break;
                default:
                    break;
            }
        }
        return executor.update(ms, paramObj);
    }

    /**
     * 獲取用戶信息
     *
     * @return 返回用戶信息
     */
    private UserInfo getUserInfo() {
        UserInfo userInfo = null;
        try {
            userInfo = UserInfoUtils.getUserInfo();
        } catch (final Exception ex) {
        }
        if (userInfo == null) {
            return null;
        }
        return userInfo;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章