I'll update my second paragraph to be clearer then I'll answer your questions.
"In the second case [i]the managed instance in the PersistenceContext does not contain the newly updated version[/i] so the merge passes the version check. On Commit the version numbers are checked against the database and an OptimisticLockException is thrown by TopLink and wrapped in a TransactionRollbackException as required by the specification. TopLink does not automatically refresh the data in the cache in this case because when the exception is generated by TopLink TopLink is still in the transaction and could be accessing uncommitted data. An enhancement should be added to have TopLink invalidate that instance in the cache though."
In both cases you should be merging detached Entities from the client not managed Entities. If you were calling merge on managed Entities then neither case would throw an OptimisticLockException as the instances would be identical.
Perhaps you could give a detailed description of the environment you are in (ie. what and where is the application client. What code is inside of the SessionBeans, what is and how often does this external application update the database).
In the second case are you loading the Object that causes the OptimisticLockException directly or is it referenced from another Entity that you are loading? On an OptimisticLockException TopLink will mark the offending object for refresh but may not know that this object is referenced from another object. Unless you later actually em.find() or perform a query for the offending object it will not be refreshed. Calling em.find() on the related object could reduce the amount of stale data you see.
Otherwise if you know you will be accessing this object that causes the OptimisticLockException I would recommend refreshing the object through em.refresh() in a 'catch' block of your session bean.
This will limit the amount of Stale data you see but as I mentioned although stale data can be mitigated through optimized refresh/caching settings no concurrent application can ever prevent stale data.
--Gordon
[Message sent by forum member 'gyorke' (gyorke)]
http://forums.java.net/jive/thread.jspa?messageID=242383