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?
P.S.
I saw workarounds like method annotations @PreUpdate
@PrePersist
i do not think i need ones.
According to the JPA spec regarding the Calendar data type:
@Temporal - This annotation must be specified for persistent fields or properties of type java.util.Date and 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:
@UpdateTimestamp
@Column
private java.sql.Timestamp modifiedDate;
@CreationTimestamp
@Column
private java.sql.Timestamp createdDate;
I think you can use @CreationTimestamp
and @UpdateTimestamp
annotations but you have to specify the TemporalType as a Timestamp.
@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 @PrePersist
and @PreUpdate
as follow:
@PrePersist
protected void onCreate() {
created = Calendar.getInstance();
}
@PreUpdate
protected void onUpdate() {
updated = Calendar.getInstance();
}
I have considered alternative solution way via spring, it works fine, and easy to shift data in tests. Original description.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With