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

相关文章

Spring Security常见问题及解决方案

《SpringSecurity常见问题及解决方案》SpringSecurity是Spring生态的安全框架,提供认证、授权及攻击防护,支持JWT、OAuth2集成,适用于保护Spring应用,需配置... 目录Spring Security 简介Spring Security 核心概念1. ​Securit

Python实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

SpringBoot改造MCP服务器的详细说明(StreamableHTTP 类型)

《SpringBoot改造MCP服务器的详细说明(StreamableHTTP类型)》本文介绍了SpringBoot如何实现MCPStreamableHTTP服务器,并且使用CherryStudio... 目录SpringBoot改造MCP服务器(StreamableHTTP)1 项目说明2 使用说明2.1

spring中的@MapperScan注解属性解析

《spring中的@MapperScan注解属性解析》@MapperScan是Spring集成MyBatis时自动扫描Mapper接口的注解,简化配置并支持多数据源,通过属性控制扫描路径和过滤条件,利... 目录一、核心功能与作用二、注解属性解析三、底层实现原理四、使用场景与最佳实践五、注意事项与常见问题六

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Java中Arrays类和Collections类常用方法示例详解

《Java中Arrays类和Collections类常用方法示例详解》本文总结了Java中Arrays和Collections类的常用方法,涵盖数组填充、排序、搜索、复制、列表转换等操作,帮助开发者高... 目录Arrays.fill()相关用法Arrays.toString()Arrays.sort()A

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter