What Hibernate LockMode do I need to read and update an object while
preventing others from doing so?
In the following code sample:
Session session = getSessionFactory().openSession();
MyObject currentState = (MyObject)
session.get(MyObject.class, id, new LockOptions(LockMode.???));
if (!statusToUpdateTo.equals(currentState.getStatus())) {
tx = session.beginTransaction();
currentState.setStatus(statusToUpdateTo);
session.save(currentState);
tx.commit();
}
session.close();
As you might hopefully interpret from the code, the idea is to check our
store and find an object with a given id, then update it to a given
status. If we find that the object is already in the status we want to
update to, we abandon doing anything. Otherwise, we update the status and
save it back to the store.
The worry I've got is that what if several of these requests come through
at once, and all try to read and update the same object? Looking through
the doco it would seem like Hibernate "usually obtains exactly the right
lock level automatically." (LockMode.class) but I'm still keen to ensure
that only one thing can read the object, make the decision that it needs
to update it, and then update it - without any other threads doing the
same to the same database entry.
From the LockMode class I think PESSIMISTIC_WRITE is what I'm after, but
can't seem to find a documentation resource that confirms this. Is anyone
able to confirm this for me, and that the above code will do what I'm
after?
No comments:
Post a Comment