1
votes

In my Entity class there are fields like dateCreated and dateUpdated. To auto-update these fields, I annotated dateCreated field with @PrePersist and dateUpdated field with @PreUpdate. It worked out for me. On creating a new entity, the dateCreated field gets updated but while updating the entity the dateCreated field becomes null and dateUpdated field gets updated. Can anyone please tell why this is happening?

I am using Hibernate 4.3.6 version and JPA 2.0

1
Can you please show some code? - Simon Martinelli

1 Answers

0
votes

The annotations below (@PrePersist, @PreUpdate) cause the methods below them to be called prior to a database insert or update to keep these fields in sync. I put them on a BaseEntity, then extend BaseEntity on all of my entities.

@PrePersist
protected void onCreation()
{
    dateCreated = Instant.now();
    dateUpdated = Instant.now();
}

@PreUpdate
protected void onUpdate() 
{
    dateUpdated = Instant.now();
}

The above assumes that you're using java.Instant but if you're using java.Date then you could use the below:

@PrePersist
protected void onCreation()
{
    dateCreated = new Date();
    dateUpdated = new Date();
}

@PreUpdate
protected void onUpdate() 
{
    dateUpdated = new Date();
}