Friday, February 28, 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;

@MappedSuperclass
public abstract class AbstractTimestampEntity {

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created", nullable = false)
    private Date created;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "updated", nullable = false)
    private Date updated;

    @PrePersist
    protected void onCreate() {
    updated = created = new Date();
    }

    @PreUpdate
    protected void onUpdate() {
    updated = new Date();
    }
}
and have all your entities extend it, for instance:
@Entity
@Table(name = "campaign")
public class Campaign extends AbstractTimestampEntity implements Serializable {
...
}

1 comment:

simashree said...

Thanks for the great information in your blog Selenium Training in Chennai