How do you support optimistic / pessimistic concurrency using NHibernate?
Optimistic concurrency control (OCC), also known as optimistic locking, is a concurrency control method applied to transactional systems such as relational database management systems and software transactional memory. OCC assumes that multiple transactions can frequently complete without interfering with each other.
An nHibernate session maintains all changes to the object model. At some point, it needs to synchronize these changes with the database.
The NHibernate session encapsulates a unit of work as specified by the unit of work pattern.
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.
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 this document.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With