问题描述
使用MybatisPlus的字段自动填充功能(FieldFill)时,报错"Column 'update_time' cannot be null"
现有配置
实体类
@Data
@Accessors(chain = true)
@TableName("user_info")
public class UserInfo {
@TableField("balance")
private Integer balance;
@TableId(value = "id", type = IdType.ID_WORKER_STR)
private String id;
@TableField("is_deleted")
@TableLogic
private Boolean deleted;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
填充配置
@Bean
public MetaObjectHandler metaObjectHandler() {
return new MetaObjectHandler() {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("create_time", LocalDateTime.now(), metaObject);
this.setFieldValByName("update_time", LocalDateTime.now(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("update_time", LocalDateTime.now(), metaObject);
}
};
}
问题排查
- 断点打到setFieldValByName()方法中,进入Debug

可以看到fieldName为“update_time”,fieldVal为当前时间
- 继续往下执行到etMeta.hasSetter(fieldName)

- 查看etMeta.的setters

总结
可以看到问题的根源所在,是因为传入的是下划线命名的update_time,而直接使用它来匹配setter的属性,并没有转换格式
这里不得不说一下MybatisPlus的配置格式统一做的并不好,因为在MybatisPlus代码生成器中配置的fieldName是用下划线命名(数据库字段)的,而在自动填充中fieldName则用驼峰命名(实体属性)
不过如果细看的话确实是有注释的,但仍然不够明确
代码生成器中:

自动填充中:

网友评论