• 用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

  • 相关阅读:
    组织机构数据隔离(上级可看下级,同级屏蔽)的高效实现思路
    .NET Core 3.x 基于AspectCore实现AOP,实现事务、缓存拦截器
    .NET Core 3.x 基于Autofac的AOP缓存
    Web开发中【密码加密】详解
    python多线程 DBUtils操作数据库
    处理MariaDB Galera cluster初始化和启动报错两例
    搭建MariaDB Galera Cluster集群 10.3.8
    AzureWeb应用作为客户端携带证书访问其他链接办法
    CTF
    [KuangBin专题四]Silver Cow Party
  • 原文地址:https://www.cnblogs.com/qingshan-tang/p/13299701.html
Copyright © 2020-2023  润新知