一、自定义插入操作插入时间注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target( {ElementType.FIELD}) public @interface CreatedOnFuncation { String value() default ""; }
二、自定义更新操作插入时间注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target( {ElementType.FIELD}) public @interface UpdatedOnFuncation { String value() default ""; }
三、实现mybatis拦截器
import com.xxx.core.aop.CreatedOnFuncation; import com.xxxx.core.aop.UpdatedOnFuncation; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import org.apache.commons.lang3.ArrayUtils; 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.sql.Timestamp; import java.util.Properties; /** * 时间拦截器. */ @EqualsAndHashCode() @Data @Accessors(chain = true) @Intercepts({@Signature( type = org.apache.ibatis.executor.Executor.class, method = "update", args = {MappedStatement.class, Object.class})}) @Component public class CreateUpdateTimeInterceptor implements Interceptor { private Properties properties; @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; // 获取 SQL 命令 SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); // 获取参数 Object parameter = invocation.getArgs()[1]; // 获取私有成员变量 Field[] declaredFields = parameter.getClass().getDeclaredFields(); if (parameter.getClass().getSuperclass() != null) { Field[] superField = parameter.getClass().getSuperclass().getDeclaredFields(); declaredFields = ArrayUtils.addAll(declaredFields, superField); } for (Field field : declaredFields) { // insert if (field.getAnnotation(CreatedOnFuncation.class) != null) { if (SqlCommandType.INSERT.equals(sqlCommandType)) { field.setAccessible(true); field.set(parameter, new Timestamp(System.currentTimeMillis())); } } // update if (field.getAnnotation(UpdatedOnFuncation.class) != null) { if (SqlCommandType.INSERT.equals(sqlCommandType) || SqlCommandType.UPDATE.equals(sqlCommandType)) { field.setAccessible(true); field.set(parameter, new Timestamp(System.currentTimeMillis())); } } } return invocation.proceed(); } @Override public Object plugin(Object target) { if (target instanceof org.apache.ibatis.executor.Executor) { return Plugin.wrap(target, this); } return target; } @Override public void setProperties(Properties prop) { this.properties = prop; } }
四、属性添加注解
五、测试
插入
更新