Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate @CreationTimestamp @UpdateTimestamp for Calendar

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.

like image 310
Sergii Avatar asked Feb 21 '17 12:02

Sergii


3 Answers

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;
like image 109
Maciej Kowalski Avatar answered Nov 14 '22 12:11

Maciej Kowalski


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();
}
like image 30
Fabien Leborgne Avatar answered Nov 14 '22 14:11

Fabien Leborgne


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

like image 2
Sergii Avatar answered Nov 14 '22 14:11

Sergii