Mybatis使用拦截器自定义审计处理
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使用拦截器自定义审计处理的更多相关文章
- MyBatis拦截器自定义分页插件实现
MyBaits是一个开源的优秀的持久层框架,SQL语句与代码分离,面向配置的编程,良好支持复杂数据映射,动态SQL;MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架.MyB ...
- Mybatis Interceptor 拦截器原理 源码分析
Mybatis采用责任链模式,通过动态代理组织多个拦截器(插件),通过这些拦截器可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最 ...
- mybatis Interceptor拦截器代码详解
mybatis官方定义:MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis ...
- Mybatis之拦截器原理(jdk动态代理优化版本)
在介绍Mybatis拦截器代码之前,我们先研究下jdk自带的动态代理及优化 其实动态代理也是一种设计模式...优于静态代理,同时动态代理我知道的有两种,一种是面向接口的jdk的代理,第二种是基于第三方 ...
- Mybatis利用拦截器做统一分页
mybatis利用拦截器做统一分页 查询传递Page参数,或者传递继承Page的对象参数.拦截器查询记录之后,通过改造查询sql获取总记录数.赋值Page对象,返回. 示例项目:https://git ...
- mybatis定义拦截器
applicationContext.xml <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlS ...
- MyBatis实现拦截器分页功能
1.原理 在mybatis使用拦截器(interceptor),截获所执行方法的sql语句与参数. (1)修改sql的查询结果:将原sql改为查询count(*) 也就是条数 (2)将语句sql进行拼 ...
- mybaits拦截器+自定义注解
实现目的:为了存储了公共字典表主键的其他表在查询的时候不用关联查询(所以拦截位置位于mybaits语句查询得出结果集后) 项目环境 :springboot+mybaits 实现步骤:自定义注解——自定 ...
- mybatis - 基于拦截器修改执行语句中的ResultMap映射关系
拦截器介绍 mybatis提供了@Intercepts注解允许开发者对mybatis的执行器Executor进行拦截. Executor接口方法主要有update.query.commit.rollb ...
随机推荐
- k8s家族Pod辅助小能手Init容器认知答疑?
k8s家族Pod辅助小能手Init容器认知答疑? k8s集群Init 容器是一种特殊容器,职责是在Pod的生命周期中作为应用容器的前置启动容器. 在很多应用场景中,在 Pod 内的应用容器正式启动之前 ...
- schtasks
schtasks create 创建新的计划任务. 语法 schtasks /create /tn TaskName /tr TaskRun /sc schedule [/mo modifier ...
- 商业智能干货分享:BI的4大核心技术
如今,我们似乎生活在一个被数据包围的时代,各方面都离不开数据.这种现象在企业的经营活动中尤为明显.在这样的市场环境下,商业智能应运而生,但你真的明白商业智能吗?以下小编将会从商业智能概念和商业智能四 ...
- python文件操作glob_os_等对比
Python标准库glob介绍 一. glob模块通配符 通配符 功能 * 匹配0或多个字符 ** 匹配所有文件,目录,子目录和子目录里面的文件 (3.5版本新增) ? 匹配一个字符,这里与正则表达式 ...
- 根据文件url,下载文件到本地
/// <summary> /// 根据文件url,下载文件到本地 /// </summary> /// <param name="fileUrl"& ...
- Json字符串和Json对象相互转换
字符串-->json对象:JSON.parse() var str = '{"code":"A001","name":"张三 ...
- (七)目标检测算法之SSD
系列博客链接: (一)目标检测概述 https://www.cnblogs.com/kongweisi/p/10894415.html (二)目标检测算法之R-CNN https://www.cnbl ...
- 05-LoadBalancer负载均衡
1.介绍 目前主流的负载方案分为以下两种: 集中式负载均衡,在消费者和服务提供方中间使用独立的代理方式进行负载,有硬件的(比如 F5),也有软件的(比如 Nginx). 客户端根据自己的请求情况做负载 ...
- Java变量,作用域,常量
JAVA变量,作用域,常量 变量 变量是什么:就是可以变化的量! Java是一种强类型的语言,每变量都必须声明其类型. Java变量是程序中最基本的存储单元,其要素包括:变量名,变量类型和作用域 格式 ...
- JZ-030-连续子数组的最大和
连续子数组的最大和 题目描述 HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学.今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和, 当向量全为正数的时候,问题很 ...