java实际开发中,数据库字段自动填充
保存或更新数据时,前端通常不会传入`isDeleted`、`createTime`、`updateTime`这三个字段,因此我们需要手动赋值。但是数据库中几乎每张表都有上述字段,所以手动去赋值就显得有些繁琐。为简化上述操作,我们可采取自动填充功能。
·
java实际开发中,数据库字段自动填充
背景
保存或更新数据时,前端通常不会传入
isDeleted、createTime、updateTime这三个字段,因此我们需要手动赋值。但是数据库中几乎每张表都有上述字段,所以手动去赋值就显得有些繁琐。为简化上述操作,我们可采取自动填充功能。
is_deleted字段
只需要在设计数据库表的时候,设置默认值

create_time和update_time字段
可使用mybatis-plus的自动填充功能,所谓自动填充,就是通过统一配置,在插入或更新数据时,自动为某些字段赋值。
@Data
public class BaseEntity implements Serializable {
@Schema(description = "主键")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@Schema(description = "创建时间")
// 插入时,自动填充create_time字段
@TableField(value = "create_time", fill = FieldFill.INSERT)
@JsonIgnore
private Date createTime;
@Schema(description = "更新时间")
// 更新时,自动填充update_time字段
@TableField(value = "update_time", fill = FieldFill.UPDATE)
@JsonIgnore
private Date updateTime;
@Schema(description = "逻辑删除")
@TableField("is_deleted")
@JsonIgnore
@TableLogic
private Byte isDeleted;
}
设置自动填充的内容
@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
}
}
在做完上述配置后,当写入数据时,Mybatis-Plus会自动将实体对象的create_time字段填充为当前时间,当更新数据时,则会自动将实体对象的update_time字段填充为当前时间。
更多推荐


所有评论(0)