Java自定义mybatis拦截器实现创建人等相关信息自动填充

本文主要是介绍Java自定义mybatis拦截器实现创建人等相关信息自动填充,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在实际项目开发中,我们可能需要在mapper层插入相应的数据,而这些数据在各个表基本都有,比如
创建时间,更新时间,创建人,更新人这些,但是又不想在每个业务中都去设置这些值,那么我们就可以使用mybatis拦截器实现数据自动填充。

一、如何实现?
1.首先添加mybatis相关依赖。

        <dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.1</version></dependency>

2.自定义mybatis拦截器。

import cn.hutool.core.date.DateUtil;
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.apache.ibatis.session.defaults.DefaultSqlSession.StrictMap;
import org.springframework.stereotype.Component;import java.lang.reflect.Field;
import java.util.*;
@Slf4j
@Component
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class MybatisInterceptor implements Interceptor {private static  final String DATETYPE="java.util.Date";private static  final String STRINGTYPE="java.lang.String";@Overridepublic Object intercept(Invocation invocation) throws Throwable {MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];// 获取sql执行类型:insert、update、select、deleteSqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();Object parameter = invocation.getArgs()[1];if (parameter == null) {return invocation.proceed();}//获取当前登录用户idString userId = TokenUtil.getConcurrentUserId();log.debug(" userId is {}....",userId);// 当sql为新增或更新类型时,自动填充操作人相关信息if (SqlCommandType.INSERT == sqlCommandType || SqlCommandType.UPDATE == sqlCommandType) {replaceEntityProperty(parameter,userId,sqlCommandType);}return invocation.proceed();}private void replaceEntityProperty(Object parameter,String userId, SqlCommandType sqlCommandType ) {// StrictMapif (parameter instanceof StrictMap) {replaceStrictMap((StrictMap) parameter,userId,sqlCommandType);} else if (parameter instanceof Map) {replaceMap((Map) parameter,userId,sqlCommandType);} else {replace(parameter,userId,sqlCommandType);}}private void replace(Object parameter,String userId,SqlCommandType sqlCommandType ) {if(SqlCommandType.INSERT == sqlCommandType){Field[] fields = getAllFields(parameter);for (Field field : fields) {try {//先设置可访问 获取值校验field.setAccessible(true);Object o = field.get(parameter);//如果不为空 则跳过 为空才设置默认值//异步执行时 取不到用户信息 这时需要手动设置if(Objects.nonNull(o)){field.setAccessible(false);continue;}if ("deleted".equals(field.getName())) {field.set(parameter, Integer.valueOf("0"));field.setAccessible(false);}else if ("createdBy".equals(field.getName())) {field.set(parameter, userId);field.setAccessible(false);}else if ("createdTime".equals(field.getName())) {String type = field.getType().getName();if(DATETYPE.equals(type)){field.set(parameter, new Date());}else if(STRINGTYPE.equals(type)) {field.set(parameter, DateUtil.formatDateTime(new Date()));}field.setAccessible(false);}else {updateProperty(parameter, field, userId);}} catch (Exception e) {log.error("failed to insert data, exception = ", e);}}}else if(SqlCommandType.UPDATE == sqlCommandType){Field[] fields = getAllFields(parameter);for (Field field : fields) {try {//先设置可访问 获取值校验field.setAccessible(true);Object o = field.get(parameter);//如果不为空 则跳过 为空才设置默认值//异步执行时 取不到用户信息 这时需要手动设置if(Objects.nonNull(o)){field.setAccessible(false);continue;}//更新时只判断是否更新的属性updateProperty(parameter, field, userId);}catch (Exception e){log.error("failed to update data, exception = ", e);}}}}private void replaceStrictMap(StrictMap map, String userId, SqlCommandType sqlCommandType ) {if (map.containsKey("collection")) {Object collection = map.get("collection");for (Object t : (Collection) collection) {replace(t,userId,sqlCommandType);}} else if (map.containsKey("array")) {Object collection = map.get("array");for (Object t : (Object[]) collection) {replace(t,userId,sqlCommandType);}}}private void replaceMap(Map map,String userId, SqlCommandType sqlCommandType) {for (Object value : map.values()) {replace(value,userId,sqlCommandType);}}private void updateProperty(Object parameter, Field field, String userId) throws IllegalAccessException {if ("updatedBy".equals(field.getName())) {field.set(parameter, userId);field.setAccessible(false);}else if ("updatedTime".equals(field.getName())) {String type = field.getType().getName();if (DATETYPE.equals(type)) {field.set(parameter, new Date());} else if (STRINGTYPE.equals(type)) {field.set(parameter, DateUtil.formatDateTime(new Date()));}field.setAccessible(false);}else {//其他属性什么也不做field.setAccessible(false);}}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}@Overridepublic void setProperties(Properties properties) {}/*** 获取类的所有属性,包括父类*/private Field[] getAllFields(Object object) {Class<?> clazz = object.getClass();List<Field> fieldList = new ArrayList<>();while (clazz != null) {fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));clazz = clazz.getSuperclass();}Field[] fields = new Field[fieldList.size()];fieldList.toArray(fields);return fields;}
}

下面是TokenUtil类,用于获取当前登录用户id。

@Slf4j
public class TokenUtil {public static String getConcurrentUserId() {ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();if (Objects.isNull(requestAttributes)) {return "";} else {HttpServletRequest request = requestAttributes.getRequest();String userId = request.getHeader("x-userId");if (!StringUtils.isBlank(userId)) {return userId;} else {Object attribute = request.getAttribute("x-userId");return Objects.nonNull(attribute) ? attribute.toString() : "";}}}
}

这样就实现了在DAO层 创建人等相关信息自动填充。

这篇关于Java自定义mybatis拦截器实现创建人等相关信息自动填充的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/459509

相关文章

mybatis执行insert返回id实现详解

《mybatis执行insert返回id实现详解》MyBatis插入操作默认返回受影响行数,需通过useGeneratedKeys+keyProperty或selectKey获取主键ID,确保主键为自... 目录 两种方式获取自增 ID:1. ​​useGeneratedKeys+keyProperty(推

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Linux在线解压jar包的实现方式

《Linux在线解压jar包的实现方式》:本文主要介绍Linux在线解压jar包的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录linux在线解压jar包解压 jar包的步骤总结Linux在线解压jar包在 Centos 中解压 jar 包可以使用 u

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被

Java中的数组与集合基本用法详解

《Java中的数组与集合基本用法详解》本文介绍了Java数组和集合框架的基础知识,数组部分涵盖了一维、二维及多维数组的声明、初始化、访问与遍历方法,以及Arrays类的常用操作,对Java数组与集合相... 目录一、Java数组基础1.1 数组结构概述1.2 一维数组1.2.1 声明与初始化1.2.2 访问