当前位置: 首页 > article >正文

自定义mybatis拦截器,在springboot项目中不起作用的解决方法

自定义mybatis拦截器,在springboot项目中不起作用的解决方法

自定义mybatis拦截器,在若依springboot项目中不起作用的原因

找到 MyBatisConfig 配置类,引入自定义配置
在这里插入图片描述
在sqlSessionFactory中添加自定义拦截器,就可以正常使用了
在这里插入图片描述

package com.lingxu.framework.config;

import com.lingxu.common.core.domain.model.LoginUser;
import com.lingxu.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod.ParamMap;
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.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * mybatis拦截器,自动注入创建人、创建时间、修改人、修改时间
 * @Author scott
 * @Date  2019-01-19
 *
 */
@Slf4j
@Component
@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) invocation.getArgs()[0];
		String sqlId = mappedStatement.getId();
		log.debug("------sqlId------" + sqlId);
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		Object parameter = invocation.getArgs()[1];
		log.debug("------sqlCommandType------" + sqlCommandType);

		if (parameter == null) {
			return invocation.proceed();
		}
		if (SqlCommandType.INSERT == sqlCommandType) {
			LoginUser sysUser = this.getLoginUser();
			Field[] fields = this.getAllFields(parameter);
			assert fields != null;
			for (Field field : fields) {
				log.debug("------field.name------" + field.getName());
				try {
					if ("createBy".equals(field.getName())) {
						field.setAccessible(true);
						Object local_createBy = field.get(parameter);
						field.setAccessible(false);
						if (local_createBy == null || local_createBy.equals("")) {
							if (sysUser != null) {
								// 登录人账号
								field.setAccessible(true);
								field.set(parameter, sysUser.getUserId());
								field.setAccessible(false);
							}
						}
					}
					if ("createName".equals(field.getName())) {
						field.setAccessible(true);
						Object local_createBy = field.get(parameter);
						field.setAccessible(false);
						if (local_createBy == null || local_createBy.equals("")) {
							if (sysUser != null) {
								// 登录人账号
								field.setAccessible(true);
								field.set(parameter, sysUser.getUser().getNickName());
								field.setAccessible(false);
							}
						}
					}
					// 注入创建时间
					if ("createTime".equals(field.getName())) {
						field.setAccessible(true);
						Object local_createDate = field.get(parameter);
						field.setAccessible(false);
						if (local_createDate == null || local_createDate.equals("")) {
							field.setAccessible(true);
							field.set(parameter, new Date());
							field.setAccessible(false);
						}
					}

				} catch (Exception e) {
				}
			}
		}
		if (SqlCommandType.UPDATE == sqlCommandType) {
			LoginUser sysUser = this.getLoginUser();
			Field[] fields = null;
			if (parameter instanceof ParamMap) {
				ParamMap<?> p = (ParamMap<?>) parameter;
				//update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
				if (p.containsKey("et")) {
					parameter = p.get("et");
				} else {
					parameter = p.get("param1");
				}
				//update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q-

				//update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
				if (parameter == null) {
					return invocation.proceed();
				}
				//update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516-

				fields = this.getAllFields(parameter);
			} else {
				fields = this.getAllFields(parameter);
			}

			for (Field field : fields) {
				field.setAccessible(true);
				log.debug("------field.name------" + field.getName());
				try {
					if ("updateBy".equals(field.getName())) {
						//获取登录用户信息
						if (sysUser != null) {
							// 登录账号
							field.set(parameter, sysUser.getUserId());
							field.setAccessible(false);
						}
					}
					if ("updateTime".equals(field.getName())) {
						field.set(parameter, new Date());
						field.setAccessible(false);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	private LoginUser getLoginUser() {
		LoginUser userNow = null;
		try {
//			try catch避免线程任务出错
			userNow = SecurityUtils.getLoginUser() != null ? SecurityUtils.getLoginUser() : null;
		} catch (Exception e) {
			//e.printStackTrace();
		}
		return userNow;
	}

	/**
	 * 获取类的所有属性,包括父类
	 *
	 * @param object
	 * @return
	 */
	public Field[] getAllFields(Object object) {
		Class<?> clazz = object.getClass();
		if(clazz==null){
			return  null;
		}
		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;
	}

}



http://www.kler.cn/a/565650.html

相关文章:

  • Unity XR-XR Interaction Toolkit开发使用方法(十三)组件介绍(XR Grab Interactable)
  • 通过 PromptTemplate 生成干净的 SQL 查询语句并执行SQL查询语句
  • Spark技术系列(一):初识Apache Spark——大数据处理的统一分析引擎
  • 【软考-架构】1.2、指令系统-存储系统-cache
  • uniapp实现的消息无限滚动组件,支持H5、微信小程序
  • python实现自己的业务集成AnythingLLM并使用eventStream方式返回前端数据
  • 依赖注入
  • Qt 上下键切换焦点及显示自定义ToolTip
  • 【MySQL】 表的约束(上)
  • R语言+AI提示词:贝叶斯广义线性混合效应模型GLMM生物学Meta分析
  • T23N 君正(Ingenic)T系列芯片是专为智能视频和物联网应用设计的高性能、低功耗处理器 提供软硬件资料及样品测试
  • 网络安全技术概述
  • 周鸿祎新能源汽车抽奖活动,抽奖券:7UTVCA
  • 辛格迪客户案例 | 甫康(上海)健康科技有限责任公司药物警戒管理系统(PVS)项目
  • 用DeepSeek生成批量删除处理 PDF第一页工具
  • 【计算机视觉】条形码与二维码识别
  • 边缘计算+多模态感知:户外监控核心技术解析与工程部署实践!户外摄像头监控哪种好?户外摄像头监控十大品牌!格行视精灵VS海康威视VS大华横评!
  • JavaEE [特殊字符] TCP协议:三次握手四次挥手全图解
  • python-leetcode-下一个排列
  • 基于定制开发开源AI大模型S2B2C商城小程序的商品选品策略研究