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;

public abstract class AbstractTimestampEntity {

    @Column(name = "created", nullable = false)
    private Date created;

    @Column(name = "updated", nullable = false)
    private Date updated;

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

    protected void onUpdate() {
    updated = new Date();
and have all your entities extend it, for instance:
@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

How to remove "Quick Access" in Explorer on Microsoft Windows 10

Just make Control + R and execute regedit. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer right side new DWORD (32...