用mybatis 攔截器 為insert update操作填充字段


背景

一般數據庫都會有update_by,update_time,create_by,create_time,del_flag這幾個字段。之前我們都是在業務中填充這幾個字段,就會產生很多與業務無關的代碼。

 

解決

發現mybatis有自己的攔截器,可以在sql執行的生命周期中調用

下面是填充字段的攔截器提供參考:

package com.sfss.interceptor;

import org.apache.commons.beanutils.BeanUtils;
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.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@Component
@Slf4j
@Intercepts(@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}))
public class AutoFillInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws IllegalAccessException, InvocationTargetException {
        fillField(invocation);
        return invocation.proceed();
    }


    private void fillField(Invocation invocation) {
        Object[] args = invocation.getArgs();
        SqlCommandType sqlCommandType = null;
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            String className = arg.getClass().getName();
            log.info(i + " 參數類型:" + className);
            //第一個參數處理。根據它判斷是否給“操作屬性”賦值。
            if (arg instanceof MappedStatement) {//如果是第一個參數 MappedStatement
                MappedStatement ms = (MappedStatement) arg;
                sqlCommandType = ms.getSqlCommandType();
                log.info("操作類型:" + sqlCommandType);
                if (sqlCommandType == SqlCommandType.INSERT || sqlCommandType == SqlCommandType.UPDATE) {//如果是“增加”或“更新”操作,則繼續進行默認操作信息賦值。否則,則退出
                    continue;
                } else {
                    break;
                }
            }

            if (sqlCommandType == SqlCommandType.INSERT) {
                for (Field f : arg.getClass().getDeclaredFields()
                ) {
                    f.setAccessible(true);
                    switch (f.getName()) {
                        case "createBy":
                            setProperty(arg, "createBy", "111");
                            break;
                        case "createTime":
                            setProperty(arg, "createTime", new Date());
                            break;
                        case "updateBy":
                            setProperty(arg, "updateBy", "111");
                            break;
                        case "updateTime":
                            setProperty(arg, "updateTime", new Date());
                            break;
                        case "delFlag":
                            setProperty(arg, "delFlag", "0");
                            break;
                    }
                }
            } else if (sqlCommandType == SqlCommandType.UPDATE) {
                for (Field f : arg.getClass().getDeclaredFields()
                ) {
                    f.setAccessible(true);
                    switch (f.getName()) {
                        case "updateBy":
                            setProperty(arg, "updateBy", "111");
                            break;
                        case "updateTime":
                            setProperty(arg, "updateTime", new Date());
                            break;
                    }
                }
            }
        }
    }

    /**
     * 為對象的操作屬性賦值
     *
     * @param bean
     */
    private void setProperty(Object bean, String name, Object value) {
        try {
            //根據需要,將相關屬性賦上默認值
            BeanUtils.setProperty(bean, name, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object plugin(Object o) {

        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

 

mybatis關於攔截器的配置

package com.sfss.backend.config;

import com.sfss.interceptor.AutoFillInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisInterceptorConfig {

    @Bean
    public String myInterceptor(SqlSessionFactory sqlSessionFactory) {
        sqlSessionFactory.getConfiguration().addInterceptor(new AutoFillInterceptor());
        return "interceptor";
    }
}

 

 

參考:

https://blog.csdn.net/cookie151/article/details/100020354

https://www.cnblogs.com/A-yes/p/10619390.html

https://blog.csdn.net/caiqing116/article/details/85146751

https://www.cnblogs.com/rulian/p/5937426.html?utm_source=itdadao&utm_medium=referral

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM