package com.gbps.biz.system.config;
import com.gbps.biz.system.entity.BaseEntity;
import com.gbps.biz.system.verification.AdminXAuthToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import java.lang.reflect.Field;
import java.util.*;
/**
* 通用字段拦截器
*
* @author wukai
*/
@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class CommonFieldInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
Class<?> classParameter = parameter.getClass();
List<Field> fieldList = new ArrayList<>(Arrays.asList(classParameter.getDeclaredFields()));
if (parameter instanceof BaseEntity) {
fieldList.addAll(Arrays.asList(BaseEntity.class.getDeclaredFields()));
}
if (ms.getSqlCommandType() == SqlCommandType.INSERT) {
this.setCommonFieldWhenInsert(fieldList, parameter);
} else if (ms.getSqlCommandType() == SqlCommandType.UPDATE) {
this.setCommonFieldWhenUpdate(fieldList, parameter);
}
} catch (Exception e) {
log.error("拦截器异常", e);
}
return invocation.proceed();
}
private void setCommonFieldWhenInsert(List<Field> fieldList, Object obj) throws Exception {
setCommonField(fieldList, obj, "createUser", "createTime");
}
private void setCommonFieldWhenUpdate(List<Field> fieldList, Object obj) throws Exception {
setCommonField(fieldList, obj, "updateUser", "updateTime");
}
private void setCommonField(List<Field> fieldList, Object obj, String user, String time) throws Exception {
for (Field field : fieldList) {
field.setAccessible(true);
if (user.equals(field.getName())) {
Long userId = AdminXAuthToken.getUserId(false);
if (Objects.nonNull(userId)) {
field.set(obj, userId);
}
} else if (time.equals(field.getName())) {
field.set(obj, new Date());
}
}
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}