NHibernate: Transactions

Transaction Locking

Summary

Locking is a mechanism that prevents concurrent access to a particular item of data. A pessimistic lock is a lock that is acquired when an item of data is read and that is held until transaction completion.

NHibernate allows you to explicitly specify a more restrictive lock for a particular transactions using a pessimistic lock. In certain circumstances, pessimistic locks may be used to prevent database-level deadlocks, which can result in transaction failure.

NHibernate defines several lock modes: LockMode.None, LockMode.Read, LockMode.Upgrade and LockMode.UpgradeNoWait.

Lock Mode Description
LockMode.None Only query the database if the object is not cached.
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.Upgrade Bypass both levels of the cache, do a version check, and obtain a database-level pessimistic upgrade lock, if that is supported.
LockMode.UpgradeNoWait Bypass both levels of the cache, do a version check, and obtain a database-level pessimistic upgrade lock, if that is supported. But don't wait for release of concurrent locks.

By specifying an explicit LockMode other than LockMode.None, NHibernate is forced to bypass both levels of the cache and go all the way to the database.

The recommended practice is not to use an explicit LockMode unless absolutely necessary. Most of the time caching is more useful than pessimistic locking.