Wednesday 1 February 2012

JPA:Versioning: thrown OptimisticLockException or StaleObjectStateException

In a project that I use versioning (@Version) I consistenly got OptimisticLockException or StaleObjectStateException. The reason was that each time I read (entityManager.find()) an entity from the db I updated an attributed of it (loadDate)...
@PostLoad
public void postLoad() throws Exception {
  loadDate = new Date();
}

So the entity was changed and it was automatically merged when the transactions contained the entityManager.find() was finished (commited). Pretty silly...

For more info on the above technique of persisting the loading time of an entity see http://micharg.blogspot.com/2012/02/jpa-how-to-persist-loading-of-entity.html

No comments:

Post a Comment