mybatis 攔截器(Interceptor)實現公共屬性賦值

1、能夠攔截的類

Executor、StatementHandler 、ParameterHandler

2、定義攔截器

package com.xxxx.interceptor;

import com.jh.erp.service.model.UserInfo;
import com.jh.erp.service.util.UserInfoUtils;
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;

/**
 * @Author: Choj
 * @CreateDateTime: 2020/1/14 20:32
 * @ModifyDateTime:
 * @Name: UserInterceptor
 * @Description: 用於賦值用戶信息的攔截器
 * @Since: 1.0
 **/
@Intercepts({@Signature(type = Executor.class, method = "update"
        , args = {MappedStatement.class, Object.class})})
public class UserInterceptor implements Interceptor {

    @Override
    public Object intercept(final Invocation invocation) throws Exception {
        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) {
                return this.executeInsert(executor, ms, paramObj);
            } else if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
                return this.executeUpdate(executor, ms, paramObj);
            } else if (ms.getSqlCommandType() == SqlCommandType.DELETE) {
                return this.executeDelete(executor, ms, paramObj);
            }
        }
        return invocation.proceed();
    }

    @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();
            final UserInfo userInfo = UserInfoUtils.getUserInfo();
            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 {
        final Field[] fields = paramObj.getClass().getDeclaredFields();
        for (final Field field : fields) {
            field.setAccessible(true);
            final String fieldName = field.getName();
            final UserInfo userInfo = UserInfoUtils.getUserInfo();
            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);
    }
}

3、註冊

package com.xxx.config;

import com.jh.erp.web.interceptor.UserInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @Author: Choj
 * @CreateDateTime: 2020/1/14 20:46
 * @ModifyDateTime:
 * @Name: UserMapperConfig
 * @Description: 修改用戶信息攔截器
 * @Since: 1.0
 **/
@Configuration
@Component
public class UserMapperConfig {

    /**
     * 註冊插件
     *
     * @return UserInterceptor
     */
    @Bean
    public String myInterceptor(final SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addInterceptor(new UserInterceptor());
        return null;
    }
}

 

發佈了68 篇原創文章 · 獲贊 9 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章