What should I use, NHiberante or Active Record?!

time to read 3 min | 594 words

I was asked this several times lately, and it is time to try to make a more coherent statement about my thought in this matter.

Active Record is a wrapper around NHibernate, which aims to make it easier to work with. The main benefit, in my opinon, is the time it takes to get a working entity from each.

In NHibernate, you need to create the XML file (sorry Pierre, if I write attributes, they are the ActiveRecord ones :-) ), which can take more time than just slapping an attribute on a property and be done with it. Active Record does a lot to infer things for you, reducing the time required to configure the mapping.

Active Record API is also much simpler (which goes both ways), which means that the learning curve is slightly lower.

However, in order to use Active Record effectively, you should understand the way that NHibernate work. Active Record also has implications on code readability in complex scenarios, basically, once you cross the one - two lines of attributes, you start to lose readability fairly fast.

Another big issue with Active Record is that it "pollute" your domain objects with persistance knowledge. This can be as explicit as inheriting from ActiveRecordBase<T> and suddenly getting Save()/Create()/Find***() methods on the object, or as implicit as having just the attributes. Either way, your domain objects suddenly "know" about persistance. 

With NHibernate, you can get a domain model where there is no reference to NHibernate at all. And for several projects, this is an important criteria. You also get a better seperation of the mapping from the objects, which is very good if you want to avoid stuff like this:

[Property("FLD_G"public string Name 

Which only serves to remind you what kind of a freak the database is underneath.

There isn't that big of a difference between Active Record and NHibernate, since Active Record tries hard to ensure that there would never be a case where you are blocked from simply calling NHibernate if you need to. The main differences are a matter of taste, architecture decisions and database complexity.

Guidance:

  • Do: prefer to use Active Record - for simplicity and ease of use.
  • Do: make sure that you understand NHibernate's Method of Operation before embarking on an important project with Active Record
  • Do: make use of the Queries capabilities on Active Record to utilize HQL and other important features on NHibernate.
  • Do not: use Active Record for legacy databases or highly unusual schemas.
  • Do not: use Active Record if you want your domain objects to be free of all persitance concerns.

I added the highly unusual schemas because I run into a lot of cases where the customer want to do something a bit extra. Custom user types, dynamic entities mapping, etc, which are better handled using NHibernate directly than going over Active Record.