Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creation timestamp and last update timestamp with Hibernate and MySQL

For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated. How would you design this?

  • What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?

  • What data types would you use in Java (Date, Calendar, long, ...)?

  • Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?

  • What annotations would you use for the mapping (e.g. @Temporal)?

I'm not only looking for a working solution, but for a safe and well-designed solution.

like image 950
ngn Avatar asked Oct 21 '08 12:10

ngn


People also ask

What does@ CreationTimestamp do?

Annotation Type CreationTimestampMarks a property as the creation timestamp of the containing entity. The property value will be set to the current VM date exactly once when saving the owning entity for the first time.

What does a timestamp do on update Current_timestamp data type?

With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP , the column has the current timestamp for its default value and is automatically updated to the current timestamp.

What is @temporal in JPA?

@Temporal is a JPA annotation that converts back and forth between timestamp and java. util. Date . It also converts time-stamp into time.


1 Answers

If you are using the JPA annotations, you can use @PrePersist and @PreUpdate event hooks do this:

@Entity @Table(name = "entities")     public class Entity {   ...    private Date created;   private Date updated;    @PrePersist   protected void onCreate() {     created = new Date();   }    @PreUpdate   protected void onUpdate() {     updated = new Date();   } } 

or you can use the @EntityListener annotation on the class and place the event code in an external class.

like image 113
Guðmundur Bjarni Avatar answered Sep 23 '22 18:09

Guðmundur Bjarni