Skip to main content

Posts

Showing posts from February, 2014

Automatic date stamping of Hibernate entities

That's what I was looking for today and I found it on Stackoverflow. You can do that with three elegant JPA annotations :

@PrePersist : automatically invoke the annoted method before persist the new entity@PreUpdate : automatically invoke the annoted method before update the existing entity@Temporal : very important to set the temporal type to timestamp. Otherwise, Hibernate could store date without hours, minutes and seconds (only day, month and year)
Enjoy Hibernate and JPA!!! (On small projects, this is always a pleasure. On large one, things are always different...)

Here is the example I found : 
import java.util.Date;import javax.persistence.Column;import javax.persistence.MappedSuperclass;import javax.persistence.PrePersist;import javax.persistence.PreUpdate;import javax.persistence.Temporal;import javax.persistence.TemporalType;@MappedSuperclasspublicabstractclassAbstractTimestampEntity{@Temporal(TemporalType.TIMESTAMP)@Column(name ="created", nullable =false)privat…