注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CreateBy {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface CreateTime {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface UpdateBy {
String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface UpdateTime {
String value() default "";
}
拦截器
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class CustomInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(CustomInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// 获取 SQL 命令
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
//只判断新增和修改
if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) {
// 获取参数
Object parameter = invocation.getArgs()[1];
//批量操作时
if (parameter instanceof MapperMethod.ParamMap) {
MapperMethod.ParamMap map = (MapperMethod.ParamMap) parameter;
Object obj = map.get("list");
List> list = (List>) obj;
if (list != null) {
for (Object o : list) {
setParameter(o, sqlCommandType);
}
}
} else {
setParameter(parameter, sqlCommandType);
}
}
return invocation.proceed();
}
public void setParameter(Object parameter, SqlCommandType sqlCommandType) throws Throwable {
Class> aClass = parameter.getClass();
Field[] declaredFields;
//如果常用字段提取了公共类 baseEntity
//判断baseEntity是否是父类
if (baseEntity.class.isAssignableFrom(aClass)) {
// 获取父类私有成员变量
declaredFields = aClass.getSuperclass().getDeclaredFields();
} else {
// 获取私有成员变量
declaredFields = aClass.getDeclaredFields();
}
for (Field field : declaredFields) {
if (SqlCommandType.INSERT.equals(sqlCommandType)) { // insert 语句插入 createBy
if (field.getAnnotation(CreateBy.class) != null) {
field.setAccessible(true);
field.set(parameter, SecurityUtils.getUsername());
}
if (field.getAnnotation(CreateTime.class) != null) { // insert 语句插入 createTime
field.setAccessible(true);
field.set(parameter, new Timestamp(System.currentTimeMillis()));
}
}
if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
if (field.getAnnotation(UpdateTime.class) != null) { // update 语句插入 updateTime
field.setAccessible(true);
field.set(parameter, new Timestamp(System.currentTimeMillis()));
}
if (field.getAnnotation(UpdateBy.class) != null) { // update 语句插入 updateBy
field.setAccessible(true);
field.set(parameter, SecurityUtils.getUsername());
}
}
}
}
}