例子:
执行修改语句时,自动更新修改时间。
(同理可得插入时,添加uuid、创建者)
import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
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.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
/**
* 拦截对象,给对象在增加、修改时添加数据。
*/
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@Component
public class OpeInfoInterceptor implements Interceptor {
public Object intercept(Invocation invocation) throws Throwable {
//获取参数
Object[] args = invocation.getArgs();
MappedStatement mappedStatement = (MappedStatement) args[0];
if (mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE) {
Object arg1 = args[1];
//如果使用@Param 来传入参数,args[1] 类型为map
if(arg1 instanceof Map){
Map map=(Map) arg1;
for (Object key : map.keySet()) {
//传入参数会重复(不知道为啥),做去重处理,只需修改其中一个参数,都能成功修改对象
if(key.toString().contains("param")) {
handelUpdateData(map.get(key));
}
}
}else {
handelUpdateData(arg1);
}
}
return invocation.proceed();
}
private void handelUpdateData(Object obj) throws IllegalAccessException {
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals("gmtModify")) {
field.setAccessible(true);
field.set(obj, new Date());
}
}
}
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
public void setProperties(Properties properties) {
}
}
只传入一个参数,结果有2个。