LockModes in Hibernate

from “Hibernate in Action” –

Hibernate defines several lock modes:
■ LockMode.NONE—Don’t go to the database unless the object isn’t in either
cache.
■ LockMode.READ—Bypass both levels of the cache, and perform a version
check to verify that the object in memory is the same version that currently
exists in the database.
■ LockMode.UPDGRADE—Bypass both levels of the cache, do a version check
(if applicable), and obtain a database-level pessimistic upgrade lock, if
that is supported.
■ LockMode.UPDGRADE_NOWAIT—The same as UPGRADE, but use a SELECT…FOR
UPDATE NOWAIT on Oracle. This disables waiting for concurrent lock releases,
thus throwing a locking exception immediately if the lock can’t be obtained.
Understanding database transactions 167
■ LockMode.WRITE—Is obtained automatically when Hibernate has written to
a row in the current transaction (this is an internal mode; you can’t specify
it explicitly).
By default, load() and get() use LockMode.NONE. LockMode.READ is most useful with
Session.lock() and a detached object. For example:
Item item = … ;
Bid bid = new Bid();
item.addBid(bid);

Transaction tx = session.beginTransaction();
session.lock(item, LockMode.READ);
tx.commit();
This code performs a version check on the detached Item instance to verify that
the database row wasn’t updated by another transaction since it was retrieved,
before saving the new Bid by cascade (assuming that the association from Item to
Bid has cascading enabled).
By specifying an explicit LockMode other than LockMode.NONE, you force Hibernate
to bypass both levels of the cache and go all the way to the database.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: