目录
前言
在公司的项目开发中,写了一个更新接口使用updateById()进行更新,然后发现其他的属性都按需更新了,但更新时间并未进行更新。
示例代码
将公司源代码进行简化转换为示例,代码如下
public void updateUser(UserVO userVO) {
//userVO中并没有修改时间字段属性
if (StringUtils.isNotBlank(userVO.getId())) { //不为空修改
User user = userMapper.selectById(userVO.getId());
BeanUtils.copyProperties(userVO,user);
userMapper.updateById(user);
}else{
throw new AppException("用户数据不存在!")
}
}
结果发现UserVO中修改的数据已经修改,但更新时间并未修改为当前时间
结论
那是因为Mybatis-Plus中字段的更新策略默认如果属性有值则不覆盖,如果填充值为null则不填充,所以当selectByld从数据库取出旧数据,然后修改自己想修改的字段后调用updateByld,会发现update time字段不会更新,这是因为selecteyld可以取类update_time的旧值、更新时填充策略会判断属性已有值,不进行自动填充,因此update_time不会自动更新。
解决方法
只需要修改mybatis-plus的默认策略就可以了,代码如下:
@Component
public class DefaultData implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
LocalDateTime curDate = LocalDateTime.now();
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, curDate);
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, curDate);
}
@Override
public void updateFill(MetaObject metaObject) {
LocalDateTime curDate = LocalDateTime.now();
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, curDate);
}
/**
* 有值覆盖
*/
@Override
public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<Object> fieldVal) {
Object obj = fieldVal.get();
if (Objects.nonNull(obj)) {
metaObject.setValue(fieldName, obj);
}
return this;
}
}
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="user对象", description="用户信息")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "用户id")
@TableId(value = "id", type = IdType.UUID)
private String id;
@ApiModelProperty(value = "用户名")
@TableField("user_name")
private String userName;
@ApiModelProperty(value = "用户密码")
@TableField("password")
private String password;
@ApiModelProperty(value = "创建时间")
@TableField(value = "create_time", fill = FieldFill.INSERT)
private String createTime;
@ApiModelProperty(value = "更新时间")
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private Integer updateTime;
@ApiModelProperty(value = "是否有效")
@TableField("is_valid")
private String isValid;
}
或者是手动设置一个值覆盖原有旧值
public void updateUser(UserVO userVO) {
//userVO中并没有修改时间字段属性
if (StringUtils.isNotBlank(userVO.getId())) { //不为空修改
User user = userMapper.selectById(userVO.getId());
BeanUtils.copyProperties(userVO,user);
user.setUpdateTime(LocalDateTime.now());
userMapper.updateById(user);
}else{
throw new AppException("用户数据不存在!")
}
}