My entity class:
@Entity
@Table(name = \"user\")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
We do this with a PreInsertEventListener and a PreUpdateEventListener :
public class TracabilityListener implements PreInsertEventListener,PreUpdateEventListener {
private void setPropertyState(Object[] propertyStates, String[] propertyNames,String propertyName,Object propertyState) {
for(int i=0;i<propertyNames.length;i++) {
if (propertyName.equals(propertyNames[i])) {
propertyStates[i]=propertyState;
return;
}
}
}
private void onInsert(Object entity,Object[] state, String[] propertyNames) {
if (entity instanceof DomainObject) {
DomainObject domainObject = (DomainObject) entity;
Date date=new Date();
domainObject.setDateCreation(date);
setPropertyState(state, propertyNames, "dateCreation", date);
domainObject.setDateModification(date);
setPropertyState(state, propertyNames, "dateModification", date);
}
}
private void onUpdate(Object entity,Object[] state, String[] propertyNames) {
if (entity instanceof DomainObject) {
DomainObject domainObject = (DomainObject) entity;
Date date=new Date();
setPropertyState(state, propertyNames, "dateCreation", domainObject.getDateCreation());
domainObject.setDateModification(date);
setPropertyState(state, propertyNames, "dateModification", date);
}
}
@Override
public boolean onPreInsert(PreInsertEvent event) {
onInsert(event.getEntity(), event.getState(), event.getPersister().getPropertyNames());
return false;
}
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
onUpdate(event.getEntity(), event.getState(), event.getPersister().getPropertyNames());
return false;
}
}
But if you want your properties to be timestamps, then they should be annotated with
@Temporal(TemporalType.TIMESTAMP)
Recently I encountered the same problem and the JPA-Annotations @PrePersist
and @PreUpdate
won't work when using the hibernate sessionFactory.
A simple way which worked for me with Hibernate 5 is to declare the field as @Version
, which will properly update the timestamp/localDateTime of the entity each time you update the database instance.