请问再插入或者更新时,有没有自动插入或更新时间的方法,create_time update_time 这些
如标题.
建议在Service层封装。
/**
-
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) { } }
其实可以直接在数据库加defalut value