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 ...
随机推荐
- Meterpreter后渗透阶段关闭防火墙与杀毒软件
- eBPF会成为服务网格的未来吗?
服务网格现状 服务网格为服务提供了复杂的应用层网络管理,如服务发现.流量路由.弹性(超时/重试/断路).认证/授权.可观察性(日志/度量/追踪)等. 在分布式应用的早期,这些要求是通过直接将所需的逻辑 ...
- 【C# 线程】转载 句柄的基本概念 .NET对象与Windows句柄
转载自:https://www.cnblogs.com/silverb/p/5300255.html 句柄的基本概念 1.句柄就是进程句柄表中的索引.2.句柄是对进程范围内一个内核对象地址的引用,一个 ...
- 在shell中变量的赋值有五种方法!
转至:https://blog.csdn.net/weibo1230123/article/details/82085226 在shell中变量的赋值有五种 :使用 read 命令,直接赋值,使用命令 ...
- c# 窗体相关操作(最大化/最小化/关闭/标题栏)
/// <summary> /// 窗体跟随鼠标移动的标记 /// </summary> private bool normalmoving = false; /// < ...
- docker学习笔记(6)——docker场景问题汇总(centos7 由于内核版本低带来的一系列问题,docker彻底卸载,安装、启动日志报错分析)
参考资料: https://nachuan.blog.csdn.net/article/details/96041277 https://www.cnblogs.com/xzkzzz/p/962765 ...
- SHA算法(及示例)演变历史
安全散列算法(英语:Secure Hash Algorithm,缩写为SHA)是一个密码散列函数家族,是FIPS所认证的安全散列算法.能计算出一个数字消息所对应到的,长度固定的字符串(又称消息摘要)的 ...
- ASP.NET Core 6框架揭秘实例演示[16]:内存缓存与分布式缓存的使用
.NET提供了两个独立的缓存框架,一个是针对本地内存的缓存,另一个是针对分布式存储的缓存.前者可以在不经过序列化的情况下直接将对象存储在应用程序进程的内存中,后者则需要将对象序列化成字节数组并存储到一 ...
- 怎么在 liunx 上安装docker
怎么在 liunx 上安装docker 作为一个非科班出身自学的小白,踩过很多的坑,特此留下记录 以下在虚拟机上示例 系统:linux(centos7) 操作方式:xshell连接终端操作 1.打开x ...
- 2022年官网下安装GIT最全版与官网查阅方法
目录 安装部署Git 1.百度搜索git,双击进入. 2.进入主页,双击如图位置. 3.进入下载列表,双击下载. 4.找到本地文件位置,双击安装,弹出界面,选择next 5.进入安装路径位置,修改路径 ...

