Tech Day #1 – NHibernate
In my previous post “My Tech ToDo – I can haz skillz?” I mentioned that I had reduced my hours at work, giving me 2 days a month to do whatever the hell I want. I have decided to devote these days to a given tech or subject to sit down and really have a chance to get acquainted.
Now, I know one day is most likely not enough to completely grok a tech or subject, hell some of them can take a lifetime to master – but it is a heck of a lot more than I have been able to do previously.
Anyway, the first of my Tech Days was dedicated to NHibernate.
What is NHibernate?
Briefly for anyone unsure:
- NHibernate is an Object Relational Mapping (ORM) tool.
- These are designed to map the complex data/models created by Object-Orientated Programming to the more simplistic scalar types used by databases.
- This problem is known as the “Object-Relational Impedance Mismatch”, which is normally overcome by creating a data access layer (DAL) which will take the complex objects, transform them for use against the actual data store (such as a database, file etc).
Good ORM’s will take all that away from you, they will take the objects you create, a map of what those objects contain and how you would like them stored and then provide an interface to perform all the database operations for you.
I decided to opt for a real quick-and-dirty app to just get playing with it to see how it worked. All I really knew about NHibernate before getting started was:
- It’s free and open source (available at Sourceforge).
- NHibernate uses an XML file to map the POCO’s (objects) to the data store – but other options are available (such as Castle Active Record).
- NHibernate’s own configuration is driven by an XML file also.
- NHibernate has quite a startup performance cost, but should be little performance loss over a regular DAL (make sure you know what a singleton is to overcome this!).
- NHibernate can cope with polymorphism in a number of ways.
- NHibernate has the ability to work with log4net to give lots of logging information.
- NHibernate can generate the database schema for you, based on your classes automatically (w00t!).
So, I had a pretty broad understanding of NHibernate (thanks a lot to @ICooper’s presentation at a local UG meeting!) to begin with, it was really a case of seeing it in action and understanding the setup process..
I thought it would be good to try and keep the application as simple as possible, so I can focus on getting NHibernate to run and play with it. Therefore the code should be considered as “Lab” code only – not recommended for production at all! I decided on:
- A standard WinForms app as the host application.
- xUnit for testing, but the test code will be mashed up with the host application (this saves on duplicating the setup for NHibernate).
- I will only work with simple CRUD operations on a simple object, leaving polymorphism for later.
- I only wanted to change the NHibernate configuration just enough to get the thing running :)
- I would use a portable MS SQL CE data file as the data store (this has both positive and negatives – local file with no SQL service required, but also needs the drivers/libraries to be imported into the project). If you are running SQL Server (and I expect all dev’s will be – if not, grab SQL Express) then it may be easier to use an MDF DB.
I originally download the reference documentation from the website, but I soon gathered that it may be out of date (followed closely and had problems getting it to run) – so I did another search and came across this article by Gabriel Schenker which is absolutely fantastic. I strongly recommended working from that article. You can see that I did.
Download & Symbols Import
Before doing ANYTHING within the application, I would strongly recommend downloading the latest release from Sourceforge and installing the symbols in the “Required_bins” folder into Visual Studio. To do this, copy the files into the “C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas” (adjust path as may be necessary) – this will give you Intellisense support for the configuration files.
SQL Server Compact Edition Required Files
If you are using the SQL Server service rather than the standalone SDF files, then obviously skip this step. If not, then please review the notes in this article under “Test the Setup”. It works fine and I would only be regurgitating content so I thought I would rather save myself some typing and share the love :)
Creating the Configuration for NHibernate
To begin with, I started to enter the configuration into the App.config file as instructed in the reference documentation. I then decided to opt against that (especially since the “.config” files for Web/Windows apps can get pretty beefy as it is) and store it in its own configuration file.
Here is the configuration file “hibernate.cfg.xml” that I used:
Now, everything in this file is important! Most of the configuration elements are reasonably self-explanatory:
- dialect tells NHibernate what version of SQL Server (or whatever DBMS you are using) – this means it can use optimisations that are available.
- connection.provider is used to tell which assembly NHibernate should use for the data connection. In this case, we are using a specialist driver for SQL Server CE so we tell it to use a separate driver.
- connection.driver_class with relation to the above, tells NHibernate what driver to actually use.
- connection.connection_string is the actual connection string to use to to connect to the data (note: if you copy the one auto-created by VS, you will need to change it slightly like the example above).
- show_sql will cause SQL statements that are executed by NHibernate to be output to the “Output” window. Very useful for debugging and just seeing what is going on under the hood.
- proxyfactory.factory_class tells NHibernate which assembly to use to generate the proxy classes that are used in the automatic schema generation. In this case, I was using Castle Active Record.
- mapping tells NHibernate that an assembly contains mapping information to be used by NHibernate (we will create the map in a bit). In this case, this is simply the assembly name of the project.
Once the configuration file is completed (be sure to use the name “hibernate.cfg.xml” – this is what NHibernate will be looking for), check the properties and ensure it’s build action is “Copy if newer” or “Copy always” (I prefer copy always), this will ensure the configuration file is output to the build directory as expected.
That should really do it for the core configuration!
Creating the POCO
The next step is to create the object that we would like to be persisted in the database. Me being a cat lover, I opted for the incredibly complex class definition of:
Glutton for punishment, right? You are probably wondering:
- Why am I using a string for an ID?
Why not? The reason in this case is mainly because I was working from an example. I will play with different types for identity soon.
- Why are the properties all virtual? This is a good question, the reason for this is because the auto-schema generator (in this case Active Record) requires that the properties to be exposed are virtual, so it can override them and do some magic.
So I now have a domain object that I wish to persist, how does the ORM know where to put the data in the database? This is where the “map” comes in..
Creating the Map File
The map file dictates to NHibernate “what goes where” in the database. This is the map file for the “Cat” class created earlier (saved as "Cat.hbm.xml”):
So, in this file we have:
- hibernate-mapping – the “namespace” attribute contains the namespace of the domain object that we are mapping, while the “assembly” attribute contains the name of the assembly in which it resides.
- class dictates the actual name of the class as well as the name of the table the objects will be stored within in the database.
- id elements contain information about how the identity of the record is both stored and generated.
- column the name of the database column the identity field is stored in (also marked as “not null” in this case so it must be set).
- generator is used to specify the generator that is used to create the unique ID. There are a whole bunch of these available.
- property elements then map the properties of the class to their related fields in the database. Constraints are applied as attributes (you can see each cat must have a name which is a maximum of 16 chars long).
And we are done! Save the file and then be sure to set its “Build Action” (in the properties window) to “Embedded Resource”. This means the XML file will actually become a part of the project assembly. When NHibernate fires up and reads it configuration, it will pick up the “mapping” elements “assembly” attribute and then hunt for XML files in the assembly. Also ensure you use the name “ClassName.hbm.xml” – convention over configuration!
We now [theoretically] have a working NHibernate configuration with a POCO that is ready to be persisted. What should we do next? Write a test!
Testing the Configuration
Using your testing framework of choice, simply add the following test code:
All we are doing here is basically newing up the NHibernate configuration (which automatically reads everything it needs) and then asking it to export/generate the database schema. If this fails, there will be something wrong with your configuration somewhere. Review and correct as necessary. I had a few errors due to bad configuration and missing SQL Server CE driver files, but I found the error messages to be very explanatory and quickly had them fixed.
Creating the Repository
DDD advocates, or even just those of us that like to write testable &, maintainable code will be familiar with the Repository Pattern. We will create a repository interface to perform the CRUD operations for our Cat data as well:
As you can see, we are not defining rocket science here, just the basic operations that we will require our data store to do. We will now create a concrete implementation of this, using NHibernate’s framework to actually do the heavy-lifting.
Creating a Static “Helper” Class
All the work that NHibernate performs takes place within what is called a Session (not to be confused with ASP.NET Sessions). The Session contains all of the reflected object data that NHibernate uses to generate the SQL statements. When the Session fires up and runs off to scan the assemblies designated in it’s configuration file. While this is useful, it is also VERY expensive, reflection is powerful but it doesn’t come cheap! Therefore, it makes sense to create a helper class to keep a reference to the Session so we only ever have to create it once. What pattern do we need here? Yup, the Singleton. Below is the code I used for the static helper class:
Note the singleton ISessionFactory – this is the object that does the heavy reflection stuff. We then have some static utility methods to get the current session and close it etc.
The Cat Repository
Quite a bit of content in there, I again recommend going through this article to see how it is put together (a lot of the code was modelled from there). The repository pattern is much loved by DDD and Testing advocates, makes sense – we don’t want to be talking to our data layer directly.
Tests for the Repository
Rather than type out all of the above code in one hit, I actually tested each part of the CRUD operation(s) one at a time and then implemented the code to pass the test. For completeness, here is the test code used:
Whoa! Hang on a Minute! Where’s the Difference?
Yup, at this point I was first thinking the same.. Up until now we have done pretty much the same as we would normally do:
- Create some POCO’s which represent our domain model.
- Create an interface for the repository.
- Implement the interface, taking the POCO’s and then creating some DAL code to persist them.
All we have actually done is just waste time messing around with creating XML files, right?
It has not been a waste of time! The benefit here is maintenance. Think about it, if we added one single property to a class, we would then need to go through all the CRUD operations within the DAL (or perhaps stored procedures) and update their parameters. All we need to do with NHibernate is add a single “property” element to the mapping file and we are done. Also remember that the database schema can be generated for you. This makes development much quicker where the domain model can be evolving quickly and you are struggling to keep the database relational model up to date. All this goes away with an ORM.
A really useful day. I had a lot of fun having finally got the chance to sit down and get a NHibernate app up and running. Am I now an NHibernate expert? No of course not! But this is not the aim of the “Tech Days”, the point of these days is to actually give me a chance to sit down and give a tech a fair shot at convincing me to invest more time into it.
I found NHibernate to be relatively quick to understand, especially once you have these core concepts down:
- The hibernate.cfg.xml configures NHibernate.
- The ClassName.hbm.xml files map the object data to fields in the database.
- The Session is used to perform a “Unit of Work”.. I started off thinking these are essentially SQL Transactions. While this is not technically correct (you perform Transactions within a Session) – the concept is very similar. A Unit of Work essentially tracks the changes made to objects (without changing the database) – when the Session is flushed, then the database is updated (using Transactions as well). This provides a real safe pattern to work with.
- The difference between how Object models work and Relational Databases is known as the “Object-Relational Impedance Mismatch”. This is just nerd-speak for “they are different”, we have all played with that stupid ball and shape thing right? Same thing, you can’t fit a square in a triangle hole.
- NHibernate has some up-front cost both in terms of development and application performance. However, the ease of maintenance it creates will likely pay you back very quickly. The lack of requirement for a real DAL can mean you focus on writing the code to solve the problem - not the problem of saving the solutions data for the original problem!
Now, I didn’t intend for this post to be any sort of tutorial. More of an overview of what I did on my first tech day, a chance to see some of the code and hopefully explain what I have learned in a way that helps others.
If anyone feels that I have misinterpreted any of the information I came across on my travels, please feel free to comment and put me straight!