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 ...
随机推荐
- pytest(3)-测试命名规则
前言 在自动化测试项目中,单元测试框架运行时需要先搜索测试模块(即测试用例所在的.py文件),然后在测试模块中搜索测试类或测试函数,接着在测试类中搜索测试方法,最后加入到队列中,再按执行顺序执行测试. ...
- Acme-https证书申请
Linux下使用acme.sh 配置https 免费证书 简单来说acme.sh 实现了 acme 协议, 可以从 let's encrypt 生成免费的证书. acme.sh 有以下特点: 一个纯粹 ...
- Understanding JSON Schema
json schema 在线校验器 译自:Understanding JSON Schema { "type": "object", "propert ...
- leetcode算法13.罗马数字转整数
哈喽!大家好,我是[学无止境小奇],一位热爱分享各种技术的博主! [学无止境小奇]的创作宗旨:每一条命令都亲自执行过,每一行代码都实际运行过,每一种方法都真实实践过,每一篇文章都良心制作过. [学无止 ...
- BI工具有多重要?凭什么得到各类企业的热烈追捧?
近年来,应用BI工具的企业越来越多,企业对BI工具的重视说明企业了解.认识到了数据的价值.数据分析工具已经渐渐成为企业日常经营管理活动中不可或缺的一项重要工作内容.但是你知道企业应该如何挑选BI工具吗 ...
- 广州市首批!Smartbi入库信创产品资源池,引领国产BI软件崛起
为贯彻落实软件高质量发展战略,加快建设有影响力的信息技术创新(简称"信创")资源池,广州市工业和信息化局经征集申报.专家评审.现场考察等多个环节,发布了"广州市信息技术应 ...
- 【windows 操作系统】进程控制块(PCB)
转载地址:https://blog.csdn.net/qq_38499859/article/details/80057427一.目录文章目录 操作系统3 ----进程控制块(PCB)详解 ...
- 在linux上oracle服务启动停止详细
转至:https://www.cnblogs.com/baihuitestsoftware/articles/6365431.html 在CentOS 6.3下安装完Oracle 10g R2,重开机 ...
- Zookeeper集群搭建及原理
1 概述 1.1 简介 ZooKeeper 是 Apache 的一个顶级项目,为分布式应用提供高效.高可用的分布式协调服务,提供了诸如数据发布/订阅.负载均衡.命名服务.分布式协调/通知和分布式锁等分 ...
- urllib-访问网页的两种方式:GET与POST
学习自:https://www.jianshu.com/p/4c3e228940c8 使用参数.关键字访问服务器 访问网络的两种方法: 1.GET 利用参数给服务器传递信息 参数data为dict类型 ...

