I am using Hibernate 2.6 with hibernate-entitymanager. I am trying to catch and handle situations when 2 transactions conflict on an object. Here is what happens:
Two threads are updating a single object wich has a @Version field. The thread which looses commit race logs StaleObjectStateException on flush. The exception is not thrown, it is just logged. I guess the transaction is marked rollback-only at that moment.
After that when the thread tries to perform commit it fails with RollbackException. I did not find a way to find out in the code why the transaction is rolled back.
Is there a way to catch and handle such situations in the code? Basicly I want to catch StaleObjectStateException, but the problem is - it is not thrown.
UPDATE: The thing I am trying to accomplish from the birds eye view is the following:
I have a J2EE app running under JBoss. It has some internal timer-invoked services and the ones invoked from the UI. It also has one critical entity. I need to ensure that different threads can not update objects of that entity class simultaniously because it may result in data inconsistency. This is why I am implementing optimistic locking.
When an optimistick lock problem occurs I am trying to handle this situation generally. I want to catch it at the very high level and show a valid user message (in my case the highest level is ExceptionMapper for RestEasy). The problem is - when I catch RollbackException - it is already too late.
I do not flush manually. Most of my EJBs use CMT and the sessions are flushed automatically.