Mybatis拦截器实现公共字段填充的示例代码

 更新时间:2024年12月12日 10:12:27   作者:WuWuII  
本文介绍了使用Spring Boot和MyBatis实现公共字段的自动填充功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

说明

基于springBoot+mybatis,三步完成

  • 编写注解,然后将注解放在对应的想要填充的字段上
  • 编写拦截器
  • 注册拦截器

注解

AutoId

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AutoId {
    IdType type() default IdType.SNOWFLAKE;
    enum IdType{
        UUID,
        SNOWFLAKE,
    }
}

CreateTime

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CreateTime {
    String value() default "";
}

UpdateTime

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface UpdateTime {
    String value() default "";
}

Mybatis拦截器

根据实体来选一种就行

实体没有父类的情况

import cn.hutool.core.util.IdUtil;
import com.example.mybatisinterceptor.annotation.AutoId;
import com.example.mybatisinterceptor.annotation.CreateTime;
import com.example.mybatisinterceptor.annotation.UpdateTime;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * Mybatis拦截器实现类,用于在插入或更新操作中自动处理创建时间、更新时间和自增ID。
 */
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    /**
     * 对执行的SQL命令进行拦截处理。
     * 
     * @param invocation 拦截器调用对象,包含方法参数和目标对象等信息。
     * @return 继续执行目标方法后的返回结果。
     * @throws Throwable 方法执行可能抛出的异常。
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
            Object parameter = invocation.getArgs()[1];
            if (parameter instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                Object obj = map.get("list");
                List<?> list = (List<?>) obj;
                if (list != null) {
                    for (Object o : list) {
                        setParameter(o, sqlCommandType);
                    }
                }
            } else {
                setParameter(parameter, sqlCommandType);
            }
        }
        return invocation.proceed();
    }

    /**
     * 设置参数的创建时间和更新时间,以及自增ID。
     * 
     * @param parameter 待处理的参数对象。
     * @param sqlCommandType SQL命令类型,用于区分插入还是更新操作。
     * @throws Throwable 设置字段值可能抛出的异常。
     */
    public void setParameter(Object parameter, SqlCommandType sqlCommandType) throws Throwable {
        Class<?> aClass = parameter.getClass();
        Field[] declaredFields;
        declaredFields = aClass.getDeclaredFields();
        for (Field field : declaredFields) {
            LocalDateTime now = LocalDateTime.now();
            if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                if (field.getAnnotation(CreateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
                if (field.getAnnotation(AutoId.class) != null ) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.SNOWFLAKE)) {
                            field.set(parameter, IdUtil.getSnowflakeNextId());
                        } else if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.UUID)) {
                            field.set(parameter, IdUtil.simpleUUID());
                        }
                    }
                }
            }
            if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
            }
        }
    }

    /**
     * 给目标对象创建一个代理。
     * 
     * @param target 目标对象,即被拦截的对象。
     * @return 返回目标对象的代理对象。
     */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
}

实体有父类的情况

package com.kd.center.service.user.interceptor;

import cn.hutool.core.util.IdUtil;
import com.kd.common.annotation.AutoId;
import com.kd.common.annotation.CreateTime;
import com.kd.common.annotation.UpdateTime;
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 org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Component
//method = "update"拦截修改操作,包括新增
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
    	//MappedStatement包括方法名和要操作的参数值
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        //sql语句的类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        //判断是不是插入或者修改
        if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
        	//获取参数
            Object parameter = invocation.getArgs()[1];
            //是不是键值对
            if (parameter instanceof MapperMethod.ParamMap) {
                MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
                Object obj = map.get("list");
                List<?> list = (List<?>) obj;
                if (list != null) {
                    for (Object o : list) {
                        setParameter(o, sqlCommandType);
                    }
                }
            } else {
            	//设置值
                setParameter(parameter, sqlCommandType);
            }
        }
        return invocation.proceed();
    }

    /**
     * 设置值
     * @param parameter     sql中对象的值
     * @param sqlCommandType        sql执行类型
     * @throws Throwable
     */
    public void setParameter(Object parameter, SqlCommandType sqlCommandType) throws Throwable {
    	//获取对象class
        Class<?> aClass = parameter.getClass();
        //获取所有属性
        Field[] declaredFields;
        declaredFields = aClass.getDeclaredFields();
        //遍历属性
        for (Field field : declaredFields) {
        	//如果是插入语句
            if (SqlCommandType.INSERT.equals(sqlCommandType)) {
            	//获取属性的注解,如果注解是@AutoId,代表它是id
                if (field.getAnnotation(AutoId.class) != null ) {
                	//绕过检查
                    field.setAccessible(true);
                    //如果值是空的
                    if (field.get(parameter) == null) {
                    	//如果是雪花算法,就按照雪花算法生成主键id,替换参数的id
                        if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.SNOWFLAKE)) {
                            field.set(parameter, IdUtil.getSnowflakeNextId());
                        } else if (Objects.equals(field.getAnnotation(AutoId.class).type(), AutoId.IdType.UUID)) {	//否则生成简单id,替换参数的id
                            field.set(parameter, IdUtil.simpleUUID());
                        }
                    }
                }
            }
        }
		//如果是继承了基类,创建时间和修改时间都在基类中,先获取基类class
        Class<?> superclass = aClass.getSuperclass();
        //获取所有属性
        Field[] superclassFields = superclass.getDeclaredFields();
        //遍历
        for (Field field : superclassFields) {
        	//创建当前日期
            Date now=new Date();
            //如果是插入语句
            if(SqlCommandType.INSERT.equals(sqlCommandType)) {
            	//如果属性带有@CreaTime注解,就设置这个属性值为当前时间
                if (field.getAnnotation(CreateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
                //如果属性带有@UpdateTime注解,就设置这个属性值为当前时间
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
            }
            //如果是插入语句,属性带有@UpdateTime注解,就设置这个属性值为当前时间
            if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                if (field.getAnnotation(UpdateTime.class) != null) {
                    field.setAccessible(true);
                    if (field.get(parameter) == null) {
                        field.set(parameter, now);
                    }
                }
            }
        }
    }
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

}

注册插件

拦截器以插件的形式,在配置类中向SqlSessionFactoryBean中注册插件

package com.example.mybatisinterceptor.config;

import com.example.mybatisinterceptor.interceptor.MybatisInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Mybatis配置类
 * 
 * 该类用于配置Mybatis的相关设置,包括数据源和拦截器的设置,以创建SqlSessionFactory。
 */
@Configuration
public class MyConfig {

    /**
     * 创建SqlSessionFactory Bean
     * 
     * @param dataSource 数据源,用于连接数据库
     * @return SqlSessionFactory,Mybatis的会话工厂,用于创建SqlSession
     * @throws Exception 如果配置过程中出现错误,抛出异常
     * 
     * 该方法通过设置数据源和插件(MybatisInterceptor)来配置SqlSessionFactoryBean,
     * 最终返回配置好的SqlSessionFactory。
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setPlugins(new MybatisInterceptor());
        return bean.getObject();
    }

}

代码:https://gitee.com/w452339689/mybatis-interceptor

到此这篇关于Mybatis拦截器实现公共字段填充的示例代码的文章就介绍到这了,更多相关Mybatis 公共字段填充内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中File与byte[]的互转方式

    Java中File与byte[]的互转方式

    这篇文章主要介绍了Java中File与byte[]的互转方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-05-05
  • SpringMVC源码解读之 HandlerMapping - AbstractDetectingUrlHandlerMapping系列初始化

    SpringMVC源码解读之 HandlerMapping - AbstractDetectingUrlHandlerM

    这篇文章主要介绍了SpringMVC源码解读之 HandlerMapping - AbstractDetectingUrlHandlerMapping系列初始化的相关资料,需要的朋友可以参考下
    2016-02-02
  • Java高性能新一代构建工具Maven-mvnd(实践可行版)

    Java高性能新一代构建工具Maven-mvnd(实践可行版)

    这篇文章主要介绍了Java高性能新一代构建工具Maven-mvnd(实践可行版),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • Java后端Tomcat实现WebSocket实例教程

    Java后端Tomcat实现WebSocket实例教程

    WebSocket protocol 是HTML5一种新的协议。它实现了浏览器与服务器全双工通信(full-duplex)。一开始的握手需要借助HTTP请求完成握手。本文给大家介绍Java后端Tomcat实现WebSocket实例教程,感兴趣的朋友一起学习吧
    2016-05-05
  • Java 实战项目锤炼之嘟嘟健身房管理系统的实现流程

    Java 实战项目锤炼之嘟嘟健身房管理系统的实现流程

    读万卷书不如行万里路,只学书上的理论是远远不够的,只有在实战中才能获得能力的提升,本篇文章手把手带你用java+SSM+jsp+mysql+maven实现一个健身房管理系统,大家可以在过程中查缺补漏,提升水平
    2021-11-11
  • Java使用Swagger接口框架方法详解

    Java使用Swagger接口框架方法详解

    这篇文章主要介绍了Java使用Swagger接口框架方法,Swagger是一个方便我们更好的编写API文档的框架,而且Swagger可以模拟http请求调用,感兴趣的同学可以参考下文
    2023-05-05
  • 浅谈springboot项目中定时任务如何优雅退出

    浅谈springboot项目中定时任务如何优雅退出

    这篇文章主要介绍了浅谈springboot项目中定时任务如何优雅退出?具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • java实现静默加载Class示例代码

    java实现静默加载Class示例代码

    这篇文章主要给大家介绍了关于java实现静默加载Class的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用java具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
    2017-10-10
  • Spring Boot日志技术logback原理及配置解析

    Spring Boot日志技术logback原理及配置解析

    这篇文章主要介绍了Spring Boot日志技术logback原理及用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • java开源项目jeecgboot的超详细解析

    java开源项目jeecgboot的超详细解析

    JeecgBoot是一款基于BPM的低代码平台,下面这篇文章主要给大家介绍了关于java开源项目jeecgboot的相关资料,文中通过图文以及实例代码介绍的非常详细,需要的朋友可以参考下
    2022-10-10

最新评论