I want to use Hibernate�s optimistic locking but I want to be able to recover from a lock exception within the same transaction � is this possible?
We have a hierarchy of records that may be updated by multiple users during periods of high activity. These are total records and when a user is trying to update a stale record, I want to:
1)catch the optimistic lock exception 2)retrieve my original data (in user cache) and calculate deltas 3)find the latest record (which caused the optimistic lock exception � I do a flush after every save so it�s current) 4)add the deltas to the new record 5)save the updated record
The problem I�m having is at step 3. I can�t find my record because the transaction no longer exists and my session is dead. I�ve read that Hibernate errors like this are non-recoverable. Can I do this? Or do I have to implement my own user version checking to check for stale data (i.e. finding the record before I save) in order to recover programmatically?
3) find the latest record (which caused the optimistic lock exception � I do a flush after every save so it�s current)
Well, its current within the scope of your transaction (depending on your level of transaction isolation). It will not actually be the latest record after an optimistic lock failure.
The only way I can think of doing something like this is to cache your Hibenrate data seperately from Hibernate, watch for the concurrent update exception, reload the data into the session, reapply your changes (you will have to consider if the ywill they still be valid) and retry the transaction.
Not easy, and quite a big overhead to fix what should be a very occasional issue. If you are seeing lots of lock exceptions you might find it easier to redesign bits of your application so the business transactions have a smaller scope.
You do it from outside the scope of your current transaction.
Perhaps you can post some code of what you have tried? Might make a discussion a bit easier.
Joined: Jul 17, 2001
The code is all over the place essentially, what I am doing is:
1. catch stale object exception 2. try to find the record again using entityManager (to get the latest copy)
this find fails because there is no transaction.
I suspect I will have to write my own optimistic locking code because we are running ejb3 within seam and this is a seam defined transaction which was exited by the stale object exception. Normally when the user experiences this kind of error the page is exited and they are taken to a generic 'please try again' page. In my case, I want to repair and keep going. I don't think Seam and Hibernate are going to let me. We are not at a point in our app development where we can redefine transactions.