首页 > 其他分享 >自定义Mybatis拦截器实现自动添加创建人修改人等公共字段

自定义Mybatis拦截器实现自动添加创建人修改人等公共字段

时间:2022-08-23 17:34:07浏览次数:93  
标签:拦截器 自定义 Object invocation org Mybatis import public

摘要

本文通过自定义Mybatis拦截器拦截Executor接口实现在插入和修改操作时自动添加创建人修改人等公共字段,话不多说,直接上代码

定义Mybatis拦截器

package com.syb.springboottestdemo.interceptor;

import com.syb.springboottestdemo.dto.GoodsDTO;
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.apache.commons.beanutils.BeanUtils;

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

/**
* @Author: syb
* @Description: 自定义mybatis拦截器
* @DateTime: 2022/8/23 17:03
* @Params:
* @Return
*/
@Intercepts({
        @Signature(
                type = Executor.class ,
                method = "update",
                args={MappedStatement.class,Object.class})
})
/**
 * 2.各个参数的含义:
 * @Intercepts:标识该类是一个拦截器;
 * @Signature:指明自定义拦截器需要拦截哪一个类型,哪一个方法;
 *        2.1 type:对应四种类型中的一种;
 * 	2.2 method:对应接口中的哪个方法;
 * 	2.3 args:对应哪一个方法参数类型(因为可能存在重载方法);
 */
public class MybatisInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //invocation.getArgs()得到的结果就是args中的参数,第一个元素肯定是MappedStatement,第二个元素是我们传递给sql语句的参数
        //如果没有传递则只能得到一个元素,也就是invocation.getArgs().length的长度是1
        //如果相关的动态代理接口没有传递参数,则我们不需要对传递给sql语句的参数进行处理,直接放行动态代理接口方法
        if(invocation.getArgs().length == 1){
            //只要执行了invocation.proceed()方法才会对动态代理接口进行放行,否则动态代理接口不会执行
            return invocation.proceed();
        }

        //获取动态代理接口传递给sql语句的参数实体
        Object parameter = invocation.getArgs()[1];
        System.out.println(parameter);

        //获取Sql语句的类型,也即是Sql语句是增删改查中的哪一个
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

        //修改人或者是创建人
        String man = "";
        if(sqlCommandType.equals(SqlCommandType.INSERT)){
            man = "createBy";
        }
        if(sqlCommandType.equals(SqlCommandType.UPDATE)){
            man = "updateBy";
        }

        //通过反射获取我们传递给sql语句也即是动态代理接口中的实体属性
        Field[] fields = GoodsDTO.class.getDeclaredFields();
        for(Field field : fields){
            //安全性访问检查:设置为true
            field.setAccessible(true);

            String fieldName = field.getName();

            if(fieldName.equals(man)){
                BeanUtils.setProperty(parameter,man,"simple");
                System.out.println(parameter);
            }
        }

        return invocation.proceed();
    }


    @Override
    public Object plugin(Object target) {
        //plugin方法主要是将拦截器中定义的增强功能(也就是拦截器)和原来的核心对象合并起来,成为最终的核心对象wrap,然后把这个对象返回
        Object wrap = Plugin.wrap(target, this);
        return wrap;
    }

    @Override
    public void setProperties(Properties properties) {
        //这个方法里面可以取出来我们mybatis的配置文件中插件中配置的属性
    }
}

注入拦截器

package com.syb.springboottestdemo.config;

import com.syb.springboottestdemo.interceptor.MybatisInterceptor;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisConfig {
    @Bean
    ConfigurationCustomizer mybatisConfigurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.addInterceptor(new MybatisInterceptor());
            }
        };
    }
}

使用说明

在xml文件中书写时直接使用,因为参数在拦截器中已经实现了注入

<insert id="insert">
        insert into goods(name,create_by)
        values (#{name},#{createBy})
    </insert>

标签:拦截器,自定义,Object,invocation,org,Mybatis,import,public
From: https://www.cnblogs.com/simplejavahome/p/16617112.html

相关文章

  • MybatisPlus属性自动填充
    阿里巴巴开发规范,对于每一张表都因该有id(主键),createTime(创建时间),updateTime(修改时间)这三个字段主键ID我们可以使用自增,或者雪花算法创建时间修改时间我们可以使用数......
  • VUE学习-自定义修饰符
    自定义修饰符组件constmyComponent={template:`<inputtype="text":value="modelValue"@input="emitValue"/>`,props:{modelValue:String,......
  • 【SpringBoot】自定义注解实现yml格式配置文件注入
    1.创建一个starter项目(非必须,主要更好分离代码)2.创建注解文件@YamlSource@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpu......
  • springboot Failed to bind properties under 'mybatis-plus.configuration' to com.b
    启动springboot时出现错误Failedtobindpropertiesunder'mybatis-plus.configuration'tocom.baomidou.mybatisplus.core.MybatisConfiguration是因为配置文件.yml......
  • vue自定义指令的使用
    1、背景:想通过自定义指令v-hasHelp控制页面右上角是否出现帮助按钮,点击按钮可以跳转外部链接。用自定义指令的目的是方便。2、先在自己的项目中注册使用hasHelpindex.j......
  • Java精进-20分钟学会mybatis使用
    文字分享希望现在的你无论有明确具体的目标还是没有,都能重视自己的需求和目标,并且常常回顾,或许可以找一个你习惯的方式写出来,挂在哪里,电脑或日记本都好。当你疲惫或迷茫的......
  • Mybatis
    什么是MyBatis?MyBatis是一款优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射。MyBatis免除了几乎所有的JDBC代码以及设置参数和获取结果集的工作。MyBatis......
  • Win 10 中通过 VMWare 16 在 UEFI 引导模式下安装 Ubuntu 18.04 虚拟机并自定义分区
    本文使用 ZhihuOnVSCode 创作并发布 VMWare安装虚拟机时默认按照Legacy引导模式(传统BIOS)进行,无法充分发挥系统及硬件性能,本文旨在记录在Win10中通过VMWare......
  • 基于SpringSecurity的@PreAuthorize实现自定义权限校验方法
    一、前言在我们一般的web系统中必不可少的就是权限的配置,也有经典的RBAC权限模型,是基于角色的权限控制。这是目前最常被开发者使用也是相对易用、通用权限模型。当然Sprin......
  • mybatis 配置文件mybatis.xml的加载过程
    mybatis配置文件的整体加载过程mybatis几乎所有的用户相关的操作都是再SqlSession上进行的,儿sqlSession是由SqlSessionFactory调用openSession方法创建的.正常情况下......