Mybatis Plus公共字段自动填充功能
实现步骤:
1.在实体类属性上加上@TableField注解,并指定自动填充的策略
@TableField(fill = FieldFill.INSERT)//插入时填充字段 private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE)//插入、更新时填充字段 private LocalDateTime updateTime; @TableField(fill = FieldFill.INSERT)//插入时填充字段 private Long createUser;
@TableField(fill = FieldFill.INSERT_UPDATE)//插入、更新时填充字段 private Long updateUser;
2.按照框架要求编写元数据对象处理器,在此类中统一为公共字段赋值,此类需要实现MetaObjectHandler
@Component @Slf4j public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { log.info("公共字段自动填充[insert]..."); metaObject.setValue("createTime", LocalDateTime.now()); metaObject.setValue("createUser", LoginCheckFilter.threadLocal.get()); metaObject.setValue("updateTime", LocalDateTime.now()); metaObject.setValue("updateUser", LoginCheckFilter.threadLocal.get()); } @Override public void updateFill(MetaObject metaObject) { log.info("公共字段自动填充[update]..."); metaObject.setValue("updateTime", LocalDateTime.now()); metaObject.setValue("updateUser", LoginCheckFilter.threadLocal.get()); } }