设置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指定逻辑删除字段
下一篇:
向数据库中插入数据的三种方式