在使用 Hibernate 进行开发时,通常我们希望在实体对象保存(插入)或更新时,自动填充 创建时间(create time) 和 更新时间(update time) 字段。可以通过以下几种方式实现:
推荐方式:使用注解 @CreationTimestamp 和 @UpdateTimestamp
这是 Hibernate 提供的内置方式,非常简洁有效。
示例代码:
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime createdAt;
@UpdateTimestamp
private LocalDateTime updatedAt;
// getter 和 setter 省略
}
说明:
@CreationTimestamp: 只在首次插入时生效。@UpdateTimestamp: 每次更新时自动刷新时间。@Column(updatable = false): 防止createdAt在更新时被修改。
进阶方式:使用 JPA 生命周期回调方法
如果你希望自定义控制逻辑或不依赖 Hibernate 的注解,可以使用 @PrePersist 和 @PreUpdate 方法:
示例代码:
import javax.persistence.*;
import java.time.LocalDateTime;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
updatedAt = LocalDateTime.now();
}
@PreUpdate
protected void onUpdate() {
updatedAt = LocalDateTime.now();
}
// getter 和 setter 省略
}
说明:
@PrePersist:在实体首次保存前触发。@PreUpdate:在实体更新前触发。- 适合那些不使用 Hibernate 专属注解、希望保持 JPA 兼容性的项目。





苏公网安备32021302001419号