设置Mysql自动填充创建更新时间

1. 适用于数据库本身sql自动填充

  • 创建时填充时间
ALTER TABLE 表名 MODIFY COLUMN  创建字时间段名 datetime NULL DEFAULT CURRENT_TIMESTAMP;

  • 更新时刷新时间
ALTER TABLE 表名 MODIFY COLUMN  更新时间字段名 timestamp NULL DEFAULT CURRENT_TIMESTAMP 
ON UPDATE CURRENT_TIMESTAMP;

2.基于mybatis plus 自动填充:

  • 这里笔者设置的是gmtCreate为创建时间, gmtModified为更新时间, isDel逻辑删除字段默认填充为0;
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("gmtCreate", new Date(), metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
        this.setFieldValByName("isDel",0,metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("gmtModified",new Date(),metaObject); 
    }
}

重新这两个方法,分别为设置创建和更新时填充字段;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date gmtCreate;

    @ApiModelProperty(value = "更新时间")
    @TableField(fill = FieldFill.INSERT_UPDATE)
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    private Date gmtModified;

    @ApiModelProperty(value = "逻辑删除")
    @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private Integer isDel;
  • 注解@ApiModelProperty 这里使用了Swagger 的注解写注释
  • 注解@JsonFormat主要是后台到前台的时间格式的转换
  • 注解@DateTimeFormat主要是前台到后台的时间格式的转换
  • 注解@TableField(fill = FieldFill.INSERT_UPDATE) 指定添加或者更新时填充时间
  • 注解 @TableField(fill = FieldFill.INSERT)指定添加时填充时间
  • 注解@TableLogic指定逻辑删除字段
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值