I am going through Hibernate Documentation an came across the LockModes
. Are these same as Isolation levels
that we use for database? How are they diff
UPGRADE means that you want to modify the loaded object and you don't want any other process to change it while you're in the process.
It's an odd combination to use load with UPGRADE, because load is generally used just to have reference to the object to be able to use it while modifying some other object. e.g.
DomesticCat kitten = (DomesticCat)session.get(DomesticCat.class, 2L);
kitten.setParent(d1);
That is why if you use a load, Hibernate will only load it if you start referencing properties.
Isolation Levels affect what you see.
Lock Modes affect what you are allowed to do.
The normal settings for hibernate are read-committed isolation and optimistic locks.
With optimistic locking, when two people try to edit the same data at the same time, the second one to commit will get an exception.
If pessimistic locks are in use, by selecting LockMode UPGRADE, then nobody else will be allowed to alter the data until the person who asked for the Lock UPGRADE releases it.
The reason the query has to be executed as soon as you load when you upgrade is that it's implemented using the select ... for update
statement and hibernate promises you that you'll have the lock when that method returns, so it has to execute the statement right away. When you don't need to hold the lock, hibernate can be lazy and defer loading the data until you show that you actually do need it.
Generally you upgrade the lock level when you have an operation that must complete regardless of what other people are doing. For example, when it's users, you can just show them the error and they can adjust their work and try again. But if the updates are being made by a messaging server or background process, handling exceptions and trying again can be very complicated, so it might be better to just lock the record so you can be sure your update goes in.