java 用于日历的休眠 @CreationTimestamp @UpdateTimestamp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42366763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:34:25  来源:igfitidea点击:

Hibernate @CreationTimestamp @UpdateTimestamp for Calendar

javahibernatejpaorm

提问by Sergii

In my entity I have fields:

在我的实体中,我有字段:

@UpdateTimestamp
@Column
private java.util.Calendar modifiedDate;
@CreationTimestamp
@Column
private java.util.Calendar createdDate;

These fields are changed by hibernate. I see result saved to DB. In DB saved data without time, how I could explain to hibernate that calendar should be saved with current dateTime?

这些字段由休眠更改。我看到结果保存到数据库。在没有时间的 DB 保存数据中,我如何解释休眠日历应该与当前日期时间一起保存?



P.S. I saw workarounds like method annotations @PreUpdate@PrePersisti do not think i need ones.

PS我看到了像方法注释@PreUpdate@PrePersist这样的解决方法,我认为我不需要。

回答by Maciej Kowalski

According to the JPA spec regarding the Calendar data type:

根据有关日历数据类型的 JPA 规范:

@Temporal- This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar.

@Temporal- 必须为 java.util.Date 和 java.util.Calendar 类型的持久字段或属性指定此注释。

In your case you should use:

在您的情况下,您应该使用:

@Temporal(TemporalType.TIMESTAMP)

for both of the fields.

对于这两个领域。

Another solution would be to simply change from java.util.Calendar to java.sql.Timestamp:

另一种解决方案是简单地从 java.util.Calendar 更改为 java.sql.Timestamp:

@UpdateTimestamp
@Column
private java.sql.Timestamp modifiedDate;
@CreationTimestamp
@Column
private java.sql.Timestamp createdDate;

回答by Fabien Leborgne

I think you can use @CreationTimestampand @UpdateTimestampannotations but you have to specify the TemporalType as a Timestamp.

我认为您可以使用@CreationTimestamp@UpdateTimestamp注释,但您必须将 TemporalType 指定为时间戳。

@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "createdDate")
private java.util.Calendar createdDate;

@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modifiedDate")
private java.util.Calendar modifiedDate;

Otherwise, as you said you can use @PrePersistand @PreUpdateas follow:

否则,正如您所说,您可以使用@PrePersist@PreUpdate如下:

@PrePersist
protected void onCreate() {
  created = Calendar.getInstance();
}

@PreUpdate
protected void onUpdate() {
  updated = Calendar.getInstance();
}

回答by Sergii

I have considered alternative solution way via spring, it works fine, and easy to shift data in tests. Original description.

我已经考虑过通过 spring 的替代解决方案,它工作正常,并且易于在测试中移动数据。原始描述