[英]How to initialize entities fields representing their datetime of insertion into database using JPA?
我的 JPA 實體有一個這樣的字段:
@Column(nullable = false)
private LocalDateTime entryDateTime;
我希望在條目成功插入數據庫時計算entryDateTime 。
我想到了兩種方法:
使用@PostPersist
方法,在這種情況下我需要刪除@Column(nullable = false)
使用@PrePersist
方法,在這種情況下@Column(nullable = false)
可以存在,但是如果插入以某種方式失敗怎么辦? 我不希望我的object然后初始化 entryDateTime,所以我需要將其設置回 null。
設計實體可能會受到意見的影響,但我認為這個問題不是基於意見的。 我正在尋找最有效的方法,我不需要刪除@Column(nullable = false)
。 有沒有辦法做到這一點或更好的方法? 或者我應該堅持我描述的其中一種方式嗎?
您使用的是 jpa 的哪個實現?
在 Hibernate 中,您可以使用
@CreationTimestamp
在 Spring 中你可以用
@CreatedDate
在使用 PrePersist 注釋的實體 class 中創建一個方法
例如:
public class UserEntity {
private Date createdAt;
...
@PrePersist
public void prePersist() {
createdAt = new Date();
}
}
那應該工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.