Hibernate & JPA default value

  • 791
  • 0
  • 2018-02-06

Hibernate 中若想要將日期欄位設定成自動取得目前時間有幾種方法

一、使用 DB 內建的 DEFAULT

ALTER table article
ADD date datetime DEFAULT current_timestamp

然後設定 Entity 欄位的 insertable=false,避免 Hibernate 自動傳入 null 值導致 DEFAULT 設定失效

@Column(insertable=false)
private Date date;

二、使用 @CreationTimestamp

透過此 annotation 可以讓 Hibernate 自動注入系統時間

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date")
private Date createDate;

三、JPA annotation @PrePersist

@PrePersist
protected void onCreate() {
    if (myDate == null) { myDate = new Date(); }
}