Implementing "touch" on JPA entity?
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 probl开发者_如何学编程em 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!
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;
}
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
精彩评论