1

In our base entity class (that all entities derive from), we have, amongst others, 2 methods. One annotatted with @PrePersist which basically just sets the dateCreated, and the other annotated with @PreUpdate which sets the dateUpdated field.

This works perfectly, as we do not wish to set the dateUpdated field on creation. As part of the design, we also make the two methods protected so that other developers don't go and explicitly mess with those two dates (also no setters).

Also, we can easily enough extend any entity to set the dateUpdated field on creation by defining a method on the actual entity and also annotate it with @PrePersist, so this part is covered.

Now, my problem at the moment is that there is a case where we would like to explicitly update the dateUpdated field on an entity, without any data on it changing (basically touch it). Is there an elegant way of doing this? I do not really want to implement a method that changes one of it's fields and then change it back. And we would like to keep having the entities without setter methods for those fields.

Thanks!

Nico Huysamen
  • 10,217
  • 9
  • 62
  • 88

2 Answers2

7

Have you tried just changing the dateUpdated field value? I guess this should make the entity modified to Hibernate, and Hibernate would call the @PreUpdate method which would set the dateUpdated field back to the current time:

public void touch() {
    this.dateUpdated = -1;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Great stuff. I actually just remebered reading this before. Will give it a try, thanks. – Nico Huysamen May 27 '11 at 13:03
  • 1
    Works perfectly, thanks! (Except cannot do `this.dateUpdated = -1` since you cannot assign an `int` to a `Date` field, but `this.dateUpdated = null` works 100%). – Nico Huysamen May 30 '11 at 07:02
0

Annotate your dateUpdated field with @Version, remove preUpdate callback and use em.lock(entity, LockModeType.WRITE) prior commiting transaction. Remamber that entity needs to be managed in order to force version column to be updated

Marcin Michalski
  • 1,266
  • 13
  • 17
  • I don't think that will work for us. We already have a version field on the entity. Also, the version field is not strictly a date, it is an integer represented as a date. – Nico Huysamen May 27 '11 at 12:59