实现MetaObjectHandler接口
重写方法
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler
{
@Override
public void insertFill(MetaObject
metaObject) {
if (UserContext.getUser()
!= null) {
this.strictInsertFill(metaObject,
"creator", String.class, UserContext.getUser().getUsername());
}
this.strictInsertFill(metaObject,
"creationtime", LocalDateTime.class, LocalDateTime.now());
Class<?> clazz =
metaObject.getOriginalObject().getClass();
//如果存在最后更新时间
try {
Field lastupdate =
clazz.getDeclaredField("lastupdate");
this.strictInsertFill(metaObject,
"lastupdate", Timestamp.class, new Timestamp(System.currentTimeMillis()));
} catch (NoSuchFieldException
ex) {
log.info(clazz.getName()
+ "不需要保存lastupdatetime");
}
}
@Override
public void updateFill(MetaObject
metaObject) {
if (UserContext.getUser()
!= null) {
this.setFieldValByName("modifier", UserContext.getUser().getUsername(),
metaObject);
}
this.setFieldValByName("modifiedtime", LocalDateTime.now(),
metaObject);
Class<?> clazz =
metaObject.getOriginalObject().getClass();
//如果存在最后更新时间
try {
Field lastupdate =
clazz.getDeclaredField("lastupdate");
this.setFieldValByName("lastupdate", new Timestamp(System.currentTimeMillis()),
metaObject);
} catch (NoSuchFieldException
ex) {
log.info(clazz.getName()
+ "不需要保存lastupdatetime");
}
}
}
注意的是:如果存在数据不覆盖,使用strictInsertFill/strictUpdateFill。比如创建时间,创建人
如果想覆盖数据,使用setFieldValByName。比如修改时间,修改人