Hi there, I'm trying to wrap my head around using optimistic locking
properly.
When I say properly, I mean being able to recover from
StaleObjectStateExceptions and do the right thing.
So far, I have something that looks something like this:
Code:
private void updateExistingRef(Ref ref, ConnectionState state)
{
boolean committed = false;
for (int i=0; i < 2; i++)
{
if (i > 0)
{
ref = (Ref) HibernateManager.load(ref.getClass(), ref.getId());
}
try
{
updateRefProperties(ref);
state.commitTransaction(true);
committed = true;
break;
}
catch (StaleObjectStateException e)
{
state.rollbackTransaction();
state.releaseHibernateSession();
}
}
if (!committed)
{
// fallback to pessimistic locking
state.setLockMode(LockMode.UPGRADE);
ref = (Ref) HibernateManager.load(state, ref.getClass(), ref.getId());
updateRefProperties(ref);
state.commitTransaction();
}
}
HibernateManager and ConnectionState are pretty straightforward
wrappers for handling exceptions, giving access to the session and transaction, etc.
I'm just wondering what other people are doing in "the real world"
where it's unacceptable to lose data, so error recovery has to be
dealt with appropriately.
Have people come up with decent abstractions for these kind
of "recoverable/retryable" units of work, or is there a better way
of doing this in Hibernate and I've missed it, or what?
In this example, retrying is simple, all the updates are handled by
the
Code:
updateRefProperties
method, but many more
complicated examples where updates aren't isolated in the same
way could quickly get unwieldy.
Any thoughts welcome...
Hunter