tags:

views:

2897

answers:

3

How do you support optimistic / pessimistic concurrency using NHibernate?

+2  A: 

NHibernate, by default, supports optimistic concurrency. Pessimistic concurrency, on the other hand, can be accomplished through the ISession.Lock() method.

These issues are discussed in detail in Chapter 10: Transactions and Concurrency of the Hibernate Docs.

Jon Limjap
Thanks Jon for the quick reply :-)
Kevin Pang
Transactions and Concurrency docs now here: http://nhforge.org/doc/nh/en/index.html#transactions
Mauricio Scheffer
+13  A: 

NHibernate supports 2 types of optimistic concurrency.

You can either have it check dirty fields by using "optimistic-lock=dirty" attribute on the "class" element in your mapping files or you can use "optimistic-lock=version" (which is also the default). If you are using version you need to provide a "version" element in your mapping file that maps to a field in your database.

Version can be of type Int64, Int32, Int16, Ticks, Timestamp, or TimeSpan and are automatically incremented on save. See Chapter 5 in the NHibernate documentation for more info.

Ryan Rinaldi
Chapter 5 of the docs now here: http://nhforge.org/doc/nh/en/index.html#mapping
Mauricio Scheffer
+1  A: 

You can also 'just' manually compare the version numbers (assuming you've added a Version property to your entity).

Clearly Optimistic is the only sane option. Sometimes of course, we have to deal with crazy scenarios however...

ip