问题描述
在添加以及修改数据时,设置crate_time、update_time的时候经常需要重复的为字段设置相应的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @PostMapping public R<String> sava(HttpServletRequest request, @RequestBody Employee employee) { ... employee.setCreateTime(LocalDateTime.now()); employee.setUpdateTime(LocalDateTime.now());
employee.setCreateUser(empID); employee.setUpdateUser(empID); ... return R.success("添加成功"); }
@PutMapping public R<String> update(HttpServletRequest request,@RequestBody Employee employee){ ...
employee.setUpdateTime(LocalDateTime.now());
employee.setUpdateUser(empID); ... return R.success("修改成功"); }
|
我们希望在增加/更新操作的时候自动填充字段为当前的时间而不用重复设置这些字段的值
解决方法
Mybatis Plus提供了公共字段填充的功能,只需要在Bean对象中的字段上添加注解 @TableField
并设置行为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Data public class Employee implements Serializable { ... @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;
}
|
然后再实现接口 MetaObjectHandler
即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @Component @Slf4j public class MyMateObjectHandler implements MetaObjectHandler {
@Override public void insertFill(MetaObject metaObject) { metaObject.setValue("createTime", LocalDateTime.now()); metaObject.setValue("createUser",new Long(1)); metaObject.setValue("updateTime", LocalDateTime.now()); metaObject.setValue("updateUser",new Long(1)); }
@Override public void updateFill(MetaObject metaObject) { metaObject.setValue("updateTime", LocalDateTime.now()); metaObject.setValue("updateUser",new Long(1)); } }
|