Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you deal with concurrency in NHibernate?

Tags:

nhibernate

How do you support optimistic / pessimistic concurrency using NHibernate?

like image 269
Kevin Pang Avatar asked Sep 23 '08 01:09

Kevin Pang


People also ask

How does concurrency control with optimistic approach work?

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.

What does NHibernate flush do?

An nHibernate session maintains all changes to the object model. At some point, it needs to synchronize these changes with the database.

What is NHibernate session?

The NHibernate session encapsulates a unit of work as specified by the unit of work pattern.


3 Answers

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.

like image 189
Ryan Rinaldi Avatar answered Nov 16 '22 10:11

Ryan Rinaldi


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.

like image 21
Jon Limjap Avatar answered Nov 16 '22 09:11

Jon Limjap


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...

like image 23
penderi Avatar answered Nov 16 '22 10:11

penderi