Mapper icon indicating copy to clipboard operation
Mapper copied to clipboard

请问再插入或者更新时,有没有自动插入或更新时间的方法,create_time update_time 这些

Open 1571312541 opened this issue 4 years ago • 3 comments

如标题.

1571312541 avatar Nov 01 '21 13:11 1571312541

建议在Service层封装。

abel533 avatar Nov 02 '21 01:11 abel533

/**

  • mybatis拦截器, 新增修改数据时, 填充 Creator CreateTime Updater UpdateTime */ @Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})}) public class AuditFieldInterceptor implements Interceptor { private AuditFieldContextService contextService;

    private AuditFieldContextService getContextService() { if (contextService == null) { contextService = ContextUtil.getApplicationContext().getBean(AuditFieldContextService.class); } return contextService; }

    @Override public Object intercept(Invocation invocation) throws Throwable { SqlCommandType commandType = ((MappedStatement) invocation.getArgs()[0]).getSqlCommandType(); if (!(commandType == SqlCommandType.INSERT || commandType == SqlCommandType.UPDATE)) { return invocation.proceed(); }

     Object model = invocation.getArgs()[1];
     if (!(model instanceof BaseModel)) {
         return invocation.proceed();
     }
    
     getContextService();
     if (contextService == null || contextService.getSkipProcess()) {
         return invocation.proceed();
     }
    
     Field[] fields = model.getClass().getDeclaredFields();
     for (Field field : fields) {
         if (AnnotationUtils.getAnnotation(field, Creator.class) != null) {
             field.setAccessible(true);
             field.set(model, commandType == SqlCommandType.INSERT ? contextService.getUserName() : null);
         }
         if (AnnotationUtils.getAnnotation(field, CreateTime.class) != null) {
             field.setAccessible(true);
             field.set(model, commandType == SqlCommandType.INSERT ? LocalDateTime.now() : null);
         }
         if (AnnotationUtils.getAnnotation(field, Updater.class) != null) {
             field.setAccessible(true);
             field.set(model, commandType == SqlCommandType.UPDATE ? contextService.getUserName() : null);
         }
         if (AnnotationUtils.getAnnotation(field, UpdateTime.class) != null) {
             field.setAccessible(true);
             field.set(model, commandType == SqlCommandType.UPDATE ? LocalDateTime.now() : null);
         }
     }
     return invocation.proceed();
    

    }

    @Override public Object plugin(Object target) { return Plugin.wrap(target, this); }

    @Override public void setProperties(Properties properties) { } }

woochanglin avatar Nov 18 '21 15:11 woochanglin

其实可以直接在数据库加defalut value

qzmer1104 avatar Mar 04 '23 09:03 qzmer1104