mysql 过滤插件_MyBatis 插件之拦截器(Interceptor)

参考 https://blog.csdn.net/weixin_39494923/article/details/91534658

//项目实际使用  就是在你进行数据库操作时,进行数据的第二次封装

package com.yueworldframework.core.mybatis;

import com.yueworldframework.core.support.SessionHelper;

import org.apache.ibatis.executor.Executor;

import org.apache.ibatis.mapping.MappedStatement;

import org.apache.ibatis.mapping.SqlCommandType;

import org.apache.ibatis.plugin.*;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.BeanUtils;

import java.lang.reflect.Method;

import java.util.Date;

import java.util.Properties;

/**

* Created by wangbs

*/

@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})

public class AuditingInterceptor implements Interceptor {

private static final Logger logger = LoggerFactory.getLogger(AuditingInterceptor.class);

private Properties props = null;

@Override

public Object intercept(Invocation invocation) throws Throwable {

MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];

SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

if (invocation.getArgs()[1] instanceof Pojo) {

Pojo parameter = (Pojo) invocation.getArgs()[1];

if (SqlCommandType.INSERT == sqlCommandType) {

// 初始化主键ID

Method initializeUUID = BeanUtils.findDeclaredMethod(parameter.getClass(), "initializeUUID");

if (null != initializeUUID) {

initializeUUID.invoke(parameter);

}

if(null==parameter.getCreator()){

parameter.setCreator(SessionHelper.getId());

}

parameter.setUpdater(SessionHelper.getId());

parameter.setCreatedDate(new Date());

parameter.setUpdatedDate(parameter.getCreatedDate());

parameter.setVersion(1);

} else if (SqlCommandType.UPDATE == sqlCommandType) {

parameter.setUpdater(SessionHelper.getId());

parameter.setUpdatedDate(new Date());

parameter.setVersion(parameter.getVersion() + 1);

}

}

return invocation.proceed();

}

@Override

public Object plugin(Object target) {

if (target instanceof Executor) {

return Plugin.wrap(target, this);

} else {

return target;

}

}

public void setProperties(Properties properties) {

if (null != properties && !properties.isEmpty()) props = properties;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值