How do you support optimistic / pessimistic concurrency using NHibernate?
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...
Related
Can NHibernate somehow force a version number increment without locking the table?
I know I can do this to force a version number increment:
session.Lock(myEntity, LockMode.Force);
But the problem is that this will also aquire a physical lock on the table row, which causes big concurrency issues in my application.
In the Java Hibernate world, this seems to be possible:
session.lock(myEntity, LockMode.OPTIMISTIC_FORCE_INCREMENT);
NHibernate's LockMode.Force appears to be equivalent to Hibernate's LockMode.PESSIMISTIC_FORCE_INCREMENT, with no equivalent to LockMode.OPTIMISTIC_FORCE_INCREMENT.
Comparing the documention of the Java and .NET version, there seem to be several LockModes missing in NHibernate that exist in Hibernate.
Any ideas how to deal with that limitation?
If you use numeric version property you can just assign it to 0 and NHibernate will auto increment it for you.
Can someone please explain the difference between Dapper.Rainbow vs. Dapper.Contrib?
I mean when do you use SqlMapperExtensions.cs of Dapper.Contrib and when should you use Dapper.Rainbow?
I’ve been using Dapper for a while now and have wondered what the Contrib and Rainbow projects were all about myself. After a bit of code review, here are my thoughts on their uses:
Dapper.Contrib
Contrib provides a set of extension methods on the IDbConnection interface for basic CRUD operations:
Get
Insert
Update
Delete
The key component of Contrib is that it provides tracking for your entities to identify if changes have been made.
For example, using the Get method with an interface as the type constraint will return a dynamically generated proxy class with an internal dictionary to track what properties have changed.
You can then use the Update method which will generate the SQL needed to only update those properties that have changed.
Major Caveat: to get the tracking goodness of Contrib, you must use an Interface as your type constraint to allow the proxy class to be generated.
Dapper.Rainbow
Rainbow is an Abstract class that you can use as a base class for your Dapper classes to provide basic CRUD operations:
Get
Insert
Update
Delete
As well as some commonly used methods such as First (gets the first record in a table) and All (gets all results records in a table).
For all intents and purposes, Rainbow is basically a wrapper for your most commonly used database interactions and will build up the boring SQL based on property names and type constraints.
For example, with a Get operation, Rainbow will build up a vanilla SQL query and return all columns and then map those values back to the type used as the constraint.
Similarly, the insert/update methods will dynamically build up the SQL needed for an insert/update based on the type constraint's property names.
Major Caveat: Rainbow expects all your tables to have an identity column named “Id”.
Differences?
The major difference between Contrib and Rainbow is (IMO), one tracks changes to your entities, the other doesn’t:
Use Contrib when you want to be able to track changes in your entities.
Use Rainbow when you want to use something more along the lines of a standard ADO.NET approach.
On a side note: I wish I had looked into Rainbow earlier as I have built up a very similar base class that I use with Dapper.
From the article and quote #anthonyv quoted: That annoying INSERT problem, getting data into the DB
There are now 2 other APIs you can choose from as well (besides Rainbow) (for CRUD)
Dapper.Contrib and Dapper Extensions.
I do not think that one-size-fits-all. Depending on your problem and
preferences there may be an API that works best for you. I tried to
present some of the options. There is no blessed “best way” to solve
every problem in the world.
I suspect what Sam was trying to convey in the above quote and the related blog post was: Your scenario may require a lot of custom mapping (use vanilla Dapper), or it may need to track entity changes (use Contrib), or you may have common usage scenarios (use Rainbow) or you may want to use a combination of them all. Or not even use Dapper. YMMV.
This post by Adam Anderson describes the differences between several CRUD Dapper extension libraries:
Dapper Contrib (Automatic change tracking - only if dirty or not, Attributes for custom mapping, No composite key support, No manual key support)
Dapper Rainbow (Manual change tracking using Snapshotter, Attributes for custom mapping, No composite key support, No manual key support)
Dapper Extensions (No change tracking, Fluent config for custom mapping, Supports composite keys, Supports manual key specification), also includes a predicate system for simple queries (NOTE: deprecated - does not support recent Dapper versions nor .NET core)
Dapper SimpleCRUD (No change tracking, Attributes for custom mapping, No composite key support, Supports manual key specification), also includes filtering/paging helpers, async support, automatic POCO class generation (through T4)
Sam describes in details what the difference is in his post - http://samsaffron.com/archive/2012/01/16/that-annoying-insert-problem-getting-data-into-the-db-using-dapper.
Basically, its the usual not 1 size fits all answer and its up to us to decide which approach to go with based on your needs:
There are now 2 other APIs you can choose from as well (besides Rainbow) (for CRUD)
Dapper.Contrib and Dapper Extensions.
I do not think that one-size-fits-all. Depending on your problem and
preferences there may be an API that works best for you. I tried to
present some of the options. There is no blessed “best way” to solve
every problem in the world.
I have an entity with multiple fields. There are two types of actions that may be performed on it: a long one, usually initiated by the user, and a short one, which is periodically run by the system. Both of these update the entity, but they touch different fields.
There can't be two concurrent long operations or two concurrent short operations. But the system may schedule a short operation while a long operation is in progress, and the two should execute concurrently. Since they touch different fields, I believe this should be possible.
I think NHibernate's change tracking should do the trick here - i.e., if one session loads an entity and updates some fields, and another session loads the same entity and updates different fields, then the two will not collide. However, I feel I shouldn't be relying on this because it sounds like an "optimization" or an "implementation detail". I tend to think of change tracking as an optimization to reduce database traffic, I don't want the functionality of the system to depend on it. Also, if I ever decide to implement optimistic concurrency for this entity, then I risk getting a StaleObjectException, even though I can guarantee that there is no actual collision.
What would be the best way to achieve this? Should I split the entity into two? Can't this affect database consistency (e.g. what if only one "half" of the entity is in the DB)? Can I use NHibernate to explicitly set only a single field of an entity? Am I wrong in not wanting to rely on change tracking to achieve functionality?
If it matters, I'm using Fluent NHibernate.
You could map the entity using dynamic update.
dynamic-update (optional, defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed.
If you enable dynamic-update, you will have a choice of optimistic locking strategies:
version check the version/timestamp columns
all check all columns
dirty check the changed columns
none do not use optimistic locking
More information here.
In other words, what are the main reasons to use it?
Thanks
Versioning is commonly used to implement a form of concurrency. In tables that can be accessed from different sources at the same time, a column named version is used. Nhibernate notes down the version of an object when it reads it, and when it tries to update it, it first checks that the version hasn't changed. On updating a row, the version column is incremented.
As an FNH user, do you find you sometimes need to supplement FNH with an hbm file? Any relatively common edge cases where you do, if so?
Cheers,
Berryl
If you need to use named queries you will need to use an hbm file and you would probably use a named query to call a stored procedure whether this be because you have legacy stored procs to call, possibly performance or in my most recent case, to do a full text search. More info on setting this up can be found here and here.
When a bug in Fluent NHibernate prohibits something. There are less bugs each release, but you might find some eventually (the most recent is the inability to map dictionaries when certain auto mapping conventions exist)
When you have a legacy system (mapped using hbms) for which you need to add new domain objects (mapped using fnh and/or automapping).
I'm using FNH Automapping on my (so far, one and only) NHibernate project.
At first, I had to write a couple of FNH overrides to work around bugs. But the bugs were quickly fixed by the FNH team, and I was able to eliminate the overrides completely.
Never had to deal with the HBM files, and I hope it stays that way!