Locking in Hibernate by R4R Team

In the Hibernate we can define various levels of locking strategies. A lock can be applied in several ways:

1. It can done via the explicit entityManager.lock() method
2. It can done via lookup methods on EntityManager: find(), refresh()
3. It can done on queries: query.setLockMode()

Here we can use the various lock approaches:

1. OPTIMISTIC (previously READ): use an optimistic locking scheme where the version number is compared: the version number is compared and has to match before the transaction is committed.

2. OPTIMISTIC_FORCE_INCREMENT (previously WRITE): use an optimistic locking scheme but force a version number increase as well: the version number is compared and has to match before the transaction is committed.

3. PESSIMISTIC_READ: apply a database-level read lock when the lock operation is requested: roughly concurrent readers are allowed but no writer is allowed.

4. PESSIMISTIC_WRITE: apply a database-level write lock when the lock operation is requested: roughly no reader nor writer is allowed.

All these locks prevent dirty reads and non-repeatable reads on a given entity. Optimistic locks enforce the lock as late as possible hoping nobody changes the data underneath while pessimistic locks enforce the lock right away and keep it till the transaction is committed.
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!