mysql 中更新时间和创建时间的自动更新
当新增记录的时候,mysql 自动将系统的当前时间 set 到创建时间和更新时间这两个字段中。
当更新记录的时候,mysql 只 update 更新时间字段的时间,而不修改创建时间字段对应的值。
创建字段的 sql
- 创建时间字段
`creat_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP
- 更新时间字段
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
这样便不需要在代码中对记录设置创建时间和修改时间了。
上述在 navicat 中的操作: 找到相应的表—右击—>点击 设计表—>如下图

在 springboot+JPA 项目中使用
实体类头加注解
@Entity
@EntityListeners(AuditingEntityListener.class)
创建时间注解
@CreatedDate
修改时间注解
@LastModifiedDate
最后 SpringBoot 启动类加注解,我们需要在 Application 中添加一个注解
@EnableJpaAuditing
# 数据时间格式的设置
第一种(可以在 apllication.property 加入下面配置就可以)
#时间戳统一转换
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
另一种是注解的形式
@JsonFormat(timezone = 'GMT+8', pattern = 'yyyyMMddHHmmss')
private Date createTime;
- 代码实例
http://113.142.69.171:8360/fengyexjtu/spring-boot-data-jpa-example.git (opens new window)