Tip: How to handle both insert & update timestamps using Hibernate

Tuesday, December 24, 2019 Labels: , ,
We prefer to maintain the time whenever we update or insert a row in the table. If you are using JPA/Hibernate, then you can let hibernate do it for you. This way, you will be sure, that with each update, only the update time is being updated and the same is true for the insert timestamp.

Let me show you how it's easy peasy.

@CreationTimestamp
Marks 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.

Usage Example:

@CreationTimestamp
@Column(name="INSERT_TS")
private Timestamp insertTs;


@UpdateTimestamp
Marks a property as the update timestamp of the containing entity. The property value will be set to the current VM date whenever the owning entity is updated.

Usage Example:

@UpdateTimestamp
@Column(name="UPDATE_TS")
private Timestamp updateTs;

Note: You will have to import these two as well in your entity:

import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

0 comments :

Post a Comment

 
Waqas Sadiq © 2014