自动填充实体类的创建时间和最后修改时间

第一步

1
2
// 给 application 入口类添加下面的注解
@EnableJpaAuditing

第二步

1
2
// 给实体类添加下面的注释
@EntityListeners(AuditingEntityListener.class)

示例

实体类示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"}, allowGetters = true)
public class Note {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotBlank
private String title;

@NotBlank
private String content;

@Column(nullable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
@CreatedDate
private Date createdAt;

@Column(nullable = false)
@Temporal(TemporalType.TIMESTAMP)
@LastModifiedDate
private Date updatedAt;
}

完整项目示例

https://github.com/JerryLi-X/springboot-jpa-mysql-demo