void test_save_1(@Param("relatedBookCategoryEntity") RelatedBookCategoryEntity relatedBookCategoryEntity11, BookEntity bookEntity11, String categoryName11,Integer age11);
    
void test_save_2(RelatedBookCategoryEntity relatedBookCategoryEntity22, BookEntity bookEntity22, String categoryName22,Integer age22);
    
   void test_save_3(String categoryName33);
    
  

    void test_save_4( String categoryName22,Integer age22);

     

    

  void test_save_5(RelatedBookCategoryEntity relatedBookCategoryEntity22);
    

      

  

以上是测试的接口,方法签名下方图片是拦截器内部形参的值结构。

以下是Java代码,实现mybatis的Interceptor接口

package cn.dmahz.config;

import cn.dmahz.dao.mapper.RelatedBookCategoryMapper;
import cn.dmahz.entity.Base;
import cn.dmahz.entity.BookEntity;
import cn.dmahz.entity.RelatedBookCategoryEntity;
import cn.dmahz.utils.MyReflectUtils;
import cn.dmahz.utils.SecurityContextHolderUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.data.annotation.*;
import org.springframework.stereotype.Component; import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.sql.Statement;
import java.util.*; /**
* @author Dream
*/
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class }),@Signature(type= StatementHandler.class,method = "parameterize",args = {Statement.class}) })
public class MybatisEntityPluginInterceptor implements Interceptor { @Override
public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs();
if(args[0] instanceof MappedStatement){
// 映射的各种信息,SQL信息、接口方法对应的参数、接口方法的全名称等等
MappedStatement mappedStatement = (MappedStatement) args[0]; // 获取执行语句的类型
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); if(args[1] instanceof HashMap<?, ?>){
HashMap<?,?> hashMap = (HashMap<?, ?>) args[1];
// 这里分别处理每个参数的实体注入
// mappedStatement.getId() -> 获取方法的全路径 ;例如: cn.xxx.xxx.xxx.ClassName.methodName
Method methodInMapper = MyReflectUtils.getMethodInMapper(mappedStatement.getId());
String[] paramKeys = parseParamKeysByMethod(methodInMapper);
for(String key:paramKeys){
Object o = hashMap.get(key);
if(o instanceof List){
List<?> list = (List<?>) o;
for(Object entity:list){
Field[] allAuditFields = MyReflectUtils.getAllAuditFields(entity.getClass());
setAuditField(sqlCommandType,entity,allAuditFields);
}
}else if(o instanceof Base){
// 这里处理不是集合的情况,通过继承 cn.dmahz.entity.Base,可证明为Java Bean
Field[] allAuditFields = MyReflectUtils.getAllAuditFields(o.getClass());
setAuditField(sqlCommandType,o,allAuditFields);
}
}
} else if(args[1] instanceof Base){
Object o =args[1];
// 这里处理不是集合的情况,通过继承 cn.dmahz.entity.Base,可证明为Java Bean
Field[] allAuditFields = MyReflectUtils.getAllAuditFields(o.getClass());
setAuditField(sqlCommandType,o,allAuditFields);
}
} // 让拦截器继续处理剩余的操作
return invocation.proceed();
} /**
* 解析方法的形参的key值,key值用于在 ParamMap中查找值,进行填充审计字段
* @param method
*/
private String[] parseParamKeysByMethod(Method method){
ArrayList<String> keyList = new ArrayList<>();
Parameter[] parameters = method.getParameters();
for (Parameter parameter:parameters) {
Param parameterAnnotation = parameter.getAnnotation(Param.class);
if(parameterAnnotation != null){
keyList.add(parameterAnnotation.value());
}else {
// 形参名称
String name = parameter.getName();
// 类型的简写名称
// String simpleName = parameter.getType().getSimpleName();
if(StringUtils.isNotBlank(name)){
keyList.add(name);
}
}
}
return keyList.toArray(new String[0]);
} /**
* 包装一下重复的代码,方便调用
* @param sqlCommandType
* @param o
* @param fields
* @throws IllegalAccessException
*/
private void setAuditField(SqlCommandType sqlCommandType,Object o,Field[] fields) throws IllegalAccessException{
for(Field field:fields){
setAuditField(sqlCommandType,o,field);
}
} /**
* 设置审计字段,包括创建人,主键ID,创建时间,更新人,更新时间。
* @param sqlCommandType
* @param o
* @param field
* @throws IllegalAccessException
*/
private void setAuditField(SqlCommandType sqlCommandType,Object o,Field field) throws IllegalAccessException {
if(sqlCommandType == SqlCommandType.INSERT){
if(field.isAnnotationPresent(CreatedBy.class)){
String currentUserId;
try {
currentUserId = SecurityContextHolderUtils.getCurrentUserId();
} catch (NullPointerException e) {
//这里仅作测试,忽略空指针异常
currentUserId = "非Web环境,当前用户ID测试值(创建值)";
}
field.set(o,currentUserId);
}else if(field.isAnnotationPresent(CreatedDate.class)){
field.set(o,System.currentTimeMillis());
}else if(field.isAnnotationPresent(Id.class)){
String uuId = UUID.randomUUID().toString();
field.set(o,uuId.replace("-",""));
}
}else if(sqlCommandType == SqlCommandType.UPDATE){
if(field.isAnnotationPresent(LastModifiedBy.class)){
String currentUserId;
try {
currentUserId = SecurityContextHolderUtils.getCurrentUserId();
} catch (NullPointerException e) {
//这里仅作测试,忽略空指针异常
currentUserId = "非Web环境,当前用户ID测试值(更新值)";
}
field.set(o,currentUserId);
}else if(field.isAnnotationPresent(LastModifiedDate.class)){
field.set(o,System.currentTimeMillis());
}
}
} public static void main(String[] args) throws InterruptedException, NoSuchMethodException { Method test_save_1 = RelatedBookCategoryMapper.class.getDeclaredMethod("test_save_1", RelatedBookCategoryEntity.class, BookEntity.class, String.class);
// parseParamKeysByMethod(test_save_1);
}
}

Mybatis使用拦截器自定义审计处理的更多相关文章

  1. MyBatis拦截器自定义分页插件实现

    MyBaits是一个开源的优秀的持久层框架,SQL语句与代码分离,面向配置的编程,良好支持复杂数据映射,动态SQL;MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyB ...

  2. Mybatis Interceptor 拦截器原理 源码分析

    Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最 ...

  3. mybatis Interceptor拦截器代码详解

    mybatis官方定义:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...

  4. Mybatis之拦截器原理(jdk动态代理优化版本)

    在介绍Mybatis拦截器代码之前,我们先研究下jdk自带的动态代理及优化 其实动态代理也是一种设计模式...优于静态代理,同时动态代理我知道的有两种,一种是面向接口的jdk的代理,第二种是基于第三方 ...

  5. Mybatis利用拦截器做统一分页

    mybatis利用拦截器做统一分页 查询传递Page参数,或者传递继承Page的对象参数.拦截器查询记录之后,通过改造查询sql获取总记录数.赋值Page对象,返回. 示例项目:https://git ...

  6. mybatis定义拦截器

    applicationContext.xml <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlS ...

  7. MyBatis实现拦截器分页功能

    1.原理 在mybatis使用拦截器(interceptor),截获所执行方法的sql语句与参数. (1)修改sql的查询结果:将原sql改为查询count(*) 也就是条数 (2)将语句sql进行拼 ...

  8. mybaits拦截器+自定义注解

    实现目的:为了存储了公共字典表主键的其他表在查询的时候不用关联查询(所以拦截位置位于mybaits语句查询得出结果集后) 项目环境 :springboot+mybaits 实现步骤:自定义注解——自定 ...

  9. mybatis - 基于拦截器修改执行语句中的ResultMap映射关系

    拦截器介绍 mybatis提供了@Intercepts注解允许开发者对mybatis的执行器Executor进行拦截. Executor接口方法主要有update.query.commit.rollb ...

随机推荐

  1. [题解]UVA10269 Adventure of Super Mario

    链接:http://vjudge.net/problem/viewProblem.action?id=24902 描述:由城镇.村子和双向边组成的图,从A+B走到1,要求最短路.有K次瞬移的机会,距离 ...

  2. ALPS TCP新建配置——网络测试仪实操

    本文主要介绍如何在ALPS平台上Step-By-Step配置TCP新建. 一.TCP新建介绍 TCP新建速率是防火墙等设备的一个重要指标,它用来评估防火墙等设备每秒能够处理的TCP创建的速率. 信而泰 ...

  3. 医疗BI系统的数据分析是怎样的?

    在社会日益发展和信息化的过程中,已经发展处行业化.智能化的各类IT系统及子系统,如ERP.CRM.财务等等.实现经营流程数字化的同时,各行业企业的数据库日益庞大,医疗行业也不例外.我国医疗行业经过多年 ...

  4. python基础之数值类型与序列类型

    Hello大家好,我是python学习者小杨同学,已经学习python有一段时间,今天将之前学习过的内容整理一番,在这与大家分享与交流,现在开始我们的python基础知识之旅吧. 数值类型与序列类型 ...

  5. EasyUI Datagrid 数据网格

    前端用easyUI开发时,官方给的文档指导太少,网上找的又很慢,因此,我总结了一个后台返回数据后,用easyUI生成表格的方法,可编辑可分页: 1 function paginationTable(i ...

  6. TypeError

    1.only size-1 arrays can be converted to Python scalars 问题来源:需要把一个float数组A转为int,于是直接在代码中写了 B=int(A), ...

  7. Spring框架第一天(搭建项目)

    Spring框架 1.简介 1.1 Spring是什么 一个开源的框架,是JavaEE开源框架 Spring是分层的 Java SE/EE应用 full-stack 轻量级开源框架,以IoC(Inve ...

  8. C#集合,字典的运用

    三个题解释所有 using System;using System.Collections.Generic;using System.Linq;using System.Text;using Syst ...

  9. CLR的GC工作模式介绍(Workstation和Server)

    CLR的核心功能之一就是垃圾回收(garbage collection),关于GC的基本概念本文不在赘述.这里主要针对GC的两种工作模式展开讨论和研究. Workstaction模式介绍 该模式设计的 ...

  10. 基于FastAPI和Docker的机器学习模型部署快速上手

    针对前文所述 机器学习模型部署摘要 中docker+fastapi部署机器学习的一个完整示例 outline fastapi简单示例 基于文件内容检测的机器学习&fastapi 在docker ...