这只是简单拿来做个填充比如create_time,这个我一般用数据库CURRENT_TIMESTAMP. create_by这些.
更多用法,百度.
package com.sckw.transport.plugin;
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.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;
/**
* @desc:
* @author: Lt
* @date: 2024-05-15
*/@Intercepts(
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
)
@Component
public class Myplugin implements Interceptor {
//获取到拦截的对象,底层也是通过代理来实现的,实际上是拿到一个目标的代理对象
@Override
public Object plugin(Object target) {
return Plugin.wrap(target,this);
}
//获取配置文件中设置的阈值等参数
@Override
public void setProperties(Properties properties) {
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
//获取操作类型,crud
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
//获取参数
Object parameter = invocation.getArgs()[1];
Field[]fields = parameter.getClass().getDeclaredFields();
for(Field field: fields){
//注入对应的属性值
if (field.getName().equals("createBy")&&SqlCommandType.INSERT.equals(sqlCommandType)){
field.setAccessible(true);
field.set(parameter,"admin"); //这里拿到当前登录信息
}
if (field.getName().equals("updateBy")&&SqlCommandType.UPDATE.equals(sqlCommandType)){
field.setAccessible(true);
field.set(parameter,"admin"); //这里拿到当前登录信息
}
}
Object object = invocation.proceed();
return object;
}
}
已有 0 条评论