We are using managed versioning for optimistic locking.
In one case, we were hoping to apply a pessimistic locking strategy that would block one thread from even reading the object until the other thread finished commiting the changes in its transaction (thereby allowing us to apply both changes to the object without overwriting). I thought we could achieve that with the following code, which I understand would lock the database row for writing AND for reads peformed with a "select for update" query:
InstanceClass ic = session.load(InstanceClass.class, 15327l, LockMode.UPGRADE);
ic.setSomething(true);
...
tx.commit();
However, it looks like Hibernate adds the version number to the generated "select for update" statement that results from the session.load():
'select id from instance_class where id =? and version =? for update' with bind parameters: {1=15327, 2=1}
This causes me to occasionally get StaleObjectStateExceptions when the second thread is executing the session.load(). Is this version number coming from the cache? Even if the pessmistic locking was working as expected at the DB level, it seems this Exception will be thrown simply because I don't know the most recent version number when I execute the query.
I'm not sure I understand how to stop this version checking. I assumed that a database-level pessimistic lock would keep the second thread from retrieving the data until the version changed due to the first thread's commit, and this would solve our problem.
Is there any way to do this with pessimistic locking, or will I simply have to catch the StaleObjectStateException and retry?
Hibernate Version:
3.1.2
Oracle Version:
10.2.0.1.0
|