Wednesday, August 16, 2006

NHibernate + Generics = Small Codebase

My company are going to use NHibernate for a few projects we're doing. I was heavily pushing for its usage because I believe it allows OOD, DDD and TDD (all the D's). However I've been amazed to find just how easy it is to use.

Essentially myself and another developer have been putting together a team project that the existing domain classes will move into. The most time consuming part is creating the mapping files for our existing classes, but if there isn't a tool out there to do that then we can write a stupid one that does the simple stuff.

Anyway its when you put generics and NHibernate together that I think things really get good.

For example to write an integration test that tests that persistence is running well you just need to do this:

  1. Create an instance of the class your testing.
  2. Use the NHibernate session to save it to the database and then flush the session.
  3. Evict it from the session. This needs to be done because NHibernate uses an identity map so if we don't evict then it will just return the same object (from memory) when we ask for it in the next step.
  4. Get the object, by ID, from the session. Since we evicted it in the last step this will cause NHibernate to reload it from the database.
  5. Compare the two objects (I wrote a reflection based helper class that does this automatically when passed two objects).

You might ask what the point of this test is, well it verifies that my database and HBM files are correct and that everything is working end to end.

I also think its worth writing these tests because its so easy, other than the first line of code you can reuse everything from one test to another by combining NHibernate with generics. To me this is wonderful and a big advantage of moving to NHibernate.

Share This - Digg It Save to Stumble It! Kick It DZone


  1. Can you elaborate on why generics in particular are a good combination with nhibernate?

  2. Just for you I posted "NHibernate + Generics = Explained a bit better", tell me if that doesn't make more sense.

  3. Hi,

    Did you try out the NHibernate generator of GenWise Studio? It can create all those mapping, poco and factory files for you.