Wednesday, February 27, 2013

Vaadin JPAContainer JPAContainerItem.setWriteThrough(false) OptimisticLockException

I was getting an OptimisticLockException (OPE) while using Vaadin JPAContainer setWriteThrough(false)

item.setWriteThrough(false);
item.getItemProperty(...).setValue(...);

item.getItemProperty(...).setValue(...);
item.getItemProperty(...).setValue(...);
item.setWriteThrough(true);

But I did not get this error if I setwriteThrough true.

Turns out that the first case calls MutableLocalEntityProvider.updateEntity() while the second case called MutableLocalEntityProvider.updateEntityProperty(). 

JpaContainerItem holds a reference to an entity that is usually (but not always) detached. 

updateEntity() simply merges this entity to the Persistence Context and commits.  If the version doesn't match the database, the OPE is thrown.  

 updateEntityProperty fetches a fresh entity with em.find(), refreshes it, sets the new value, commits and detaches the entity.  Only a concurrent write to the database would cause a OPE.

Under both scenarios, setValue() does not cause the Item's referred entity to be refreshedthe version number does not  change.  Basically, OPE is thrown when updateEntity() called after any changes have been committed.

 

 


No comments:

Post a Comment