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 ...
随机推荐
- 在Linux发行版上使用7zip的方法
学习如何在 Ubuntu 和其他 Linux 发行版中安装和使用 7zip 7zip介绍 7Zip(更适当的写法是 7-Zip)是一种在 Windows 用户中广泛流行的归档格式.一个 7Zip 归档 ...
- WPF中常用控件(TreeView, ComboBox, DataGrid, ListView)使用MVVM模式绑定的demo
之前几篇关于TreeView的博客中只是贴了源代码,并没有把整个项目上传到github.最近就想着把我常用的几个控件做成一个demo,这样也方便自己以后查看.本人也是WPF新手,但是我并没有打算就往这 ...
- 60天shell脚本计划-9/12-渐入佳境
--作者:飞翔的小胖猪 --创建时间:2021年3月8日 --修改时间:2021年3月12日 说明 每日上传更新一个shell脚本,周期为60天.如有需求的读者可根据自己实际情况选用合适的脚本,也可在 ...
- Atcoder 229
Atcoder 229 \(D.\)Longest X 题意 给定一个长度为\(N\)的字符串\(S\),\(S\)中包含$\ .\ \(和\)\ X\ \(两种字符,现在你可以将其中\)K\(个\) ...
- websocket原理和基于c/c++实现的websocket协议栈(更新中)
参考: 博客1:http://blog.sina.com.cn/s/blog_bf397e780102w25k.html https://www.cnblogs.com/barrywxx/p/7412 ...
- JAVA_Scanner 键盘输入
键盘输入语句 介绍:在编程中,需要接收用户输入的数据,就可以使用键盘输入语句来获取.Input.java , 需要一个 扫描器(对象), 就是 Scanner 步骤: 导入该类的所在包, java.u ...
- LeetCode-023-合并K个升序链表
合并K个升序链表 题目描述:给你一个链表数组,每个链表都已经按升序排列. 请你将所有链表合并到一个升序链表中,返回合并后的链表. 示例说明请见LeetCode官网. 来源:力扣(LeetCode) 链 ...
- LeetCode-054-螺旋矩阵
螺旋矩阵 题目描述:给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素. 示例说明请见LeetCode官网. 来源:力扣(LeetCode) 链接:http ...
- 【故障公告】龙卷风来袭:突增的并发请求,撑不住的CPU
(上图是数据库连接数监控图) 非常抱歉,今天下午 16:50-17:40 期间,一场龙卷风突袭园子,突增的并发请求狂卷博客站点的 pod,由于风力巨大(70%左右的增量),pod 的 cpu 不堪重负 ...
- vm虚拟机安装CentOS8.2服务器系统
前言 开发服务器应用,需要使用到CentOS8.2,安装到虚拟机上方便快捷. 提前准备 Vmware 16虚拟机软件 下载VM16版本及以上的vmware虚拟机版本,否则没有CentOs8选 ...

