NHibernate: Transactions

Transaction Isolation Levels

Summary

Setting the transaction isolation level in NHibernate allows you to choose a good default locking strategy for all your database transactions. NHibernate doesn't add additional semantics and it uses whatever is available within a given database.

The standard isolation levels that are defined are: Read Uncommitted, Read Committed, Repeatable Read and Serializable.

Isolation Level Description
Read Uncommitted Any transaction may read any data row in the database, but a transaction may not write to a data row if another uncommitted transaction has already written to it.
It is possible that changes made by one transaction that ends up being rolled back could be committed anyway, because they could be read and then propagated by another transaction that is successful.
Read Committed An uncommitted writing transaction blocks all other transactions from accessing the data row in the database.
Using read-committed isolation for all database transactions is acceptable when using the functionality available in NHibernate for versioned data.
Repeatable Read Reading transactions block writing transactions only, and allow other reading transactions to access the data row in the database. Writing transactions block all other transactions.
It is possible that a transaction executes a query twice, and the second result set includes rows that weren't visible in the first result set. Caused by another transaction inserting new rows between the execution of the two queries.
Serializable Emulates serial transaction execution, as if transactions had been executed one after another, serially, rather than concurrently.
This isolation level tends to scale poorly and few existing applications use serializable isolation in production.

Every ADO.NET connection to a database uses the database's default isolation level. To overwrite the transaction isolation level for the ADO.NET connection, set the hibernate.connection.isolation configuration property in the NHibernate configuration.

NHibernate will then set this isolation level on every ADO.NET connection obtained from a connection pool before starting a transaction.