Welcome to GuerillaProgrammer.com Sign in | Join | Help

Syndication

Tags

    No tags have been created or used yet.
NHibernate – my crash introduction

 

I just started a new project with a new client. They have decided to use NHibernate for their data access layer. Having not used NHibernate or any of the current ORM tools this was a nice opportunity to learn something new.

NHibernate is framework that will manage persistence between your .NET objects and a back end database (SQL Server). It is an ORM tool like SubSonic, and ADO.NET Entities to name a few. Personally, I’ve avoided ORM frameworks in favor of treating a database like a database and an object like an object.

Part of the reason I’ve not bothered to learn any of the ORM frameworks is that they generally suck in my opinion. Yeah, they offer rapid application development, but I’ve not really seen anybody rave about their performance or scalability. Restaurant equivalent might be McDonalds – quick food, but they aren’t winning any awards from Zagats.

Given what an ORM tool does performance and scalability shouldn’t be a huge hurdle. In the end they all issue SQL queries against a DB. The issues crop up in design though. We want to program in an Object Oriented environment but databases are simply not OO. ORMs try to make databases look OO, but seriously – they are not. So that leaves you a choice – take the blue pill and play along with the ORM tool and pretend the DB suddenly became OO. Or take the red pill and live with having to make the translation manually.

Having lived in red pill land all this time I’m willing to give the blue pill a shot. Beside, I can always revert back to hand coding everything.

Anyway, what follows here is my introduction to NHibernate and the manner in which I’m using it.

Getting Started

First off you can grab the latest version of NHibernate from http://www.hibernate.org/. Hibernate is a Java framework that NHibernate was ported from and their web-site has a wealth of information for support. To get the actual stuff you need, click on the download link and then on the “NHibernate” download link which takes you to SourceForge. Once you’re on the actual download page get the msi. I’m using 1.2.1.GA. There is a 2.0 but it is in Alpha so I’d wait if you plan to take your stuff in to production anytime soon.

After you run the MSI you will have everything installed in Program Files. There are 3 files in the docs directory. Ignore the PDF because it duplicates the NHibernate .API.chm file (or is it the other way around?). The docs are ok, but I really think the intro stuff could be done better to make it easier for n00bs to ramp up.

After reading their quick start I almost gave up. I don’t care about Cats, my client already has a database and I need to get at it. I decided to write a simple sample application using Northwind as my source database. Just make a simple form that shows all the products in a listbox. Nothing complex for now.

Cheating

But before going on, let’s cheat a bit.

All database code is essentially the same stuff. Sure table names change, columns change, but we are always doing the same thing over and over. Sounds like an opportunity for a template. In previous episodes I talked about using the T4 template engine to do stuff. I seriously don’t have the time to be reinventing the wheel so I’m just going to start using CodeSmith.

Instead of having to write the entity classes and their DB mapping files go grab a codesmith template to help out: http://www.intesoft.net/nhibernate/. There are a few issues with this template because the author has not updated it in a very long time. However, it will do.

Run CodeSmith, open Simon’s template. You’ll see three templates – choose the one named “NHibernate.cst” and run it. Set your DB connection, which directory CodeSmith will write the files to and the other properties and then run the template. Viola! All of your entity objects are generated from the DB’s schema. It’s not all beer and skittles though – you’ve got to go in and clean up a few things first.

1. The XML namespace is wrong. The template generated one xml mapping file for each table in the database. The problem is that the namespace version needs to be 2.2 not 2.0. Just a quick search & replace job.

2. One-to-one mappings don’t work. All of the one-to-one mappings in the xml files are wrong. Go in and make the one-to-one element self closing, add a property-ref attribute whose value comes from the column tag below. Delete the column tag and the closing tag.

3. In many cases you will end up with properties that have the same name as the class. You’ll have to fix that.

4. The assembly name and the .NET namespaces need to be correct.

At this point you should be able to put all your stuff in to a project and compile it. Actually, I still had issues to address. In my opinion the template follows foreign keys too much leading to some odd class compositions. However, it is easy enough to remove the unneeded mappings and make the relationships look right.

Obviously you can go back and edit the template to fix a few of these issues (namespace, one-to-one) with very little trouble. Making the template chase foreign keys better and some of the other problems are a bit more challenging. Overall though I think investing the effort would be worthwhile if you are looking to cut down development time.

Configuration

NHibernate needs some configuration information to work. To get started grab the configuration information used in the quick start documentation (NHibernate.documentation.chm). You’ll have to change your connection string and the mapping information. There are several ways to tell NHibernate where to get its mapping file, my favorite right now is to embed the xml files as a resources and use the mapping tag to tell it the name of each resource and the name of the assembly with the resource. I tried just using the assembly tag but it didn’t work. I might have done it wrong so YMMV.

Once you have the configuration stuff done you can get down to actual coding.

Coding

The idea is that I don’t have to write any DB code. I just call some API, tell it what I want and it figures it all out for me. Overall NHibernate delivers. You have to setup a Session Factory object and then get a Session object. Once you have the session object you can start work. The first bit takes two lines:

clip_image002

Pretty easy. Then to get my products out of the database:

clip_image004

Just dump the products in to a listbox and we are done with this demo.

What wasn’t Covered

This is only a crash course that barely even scratches the surface. NHibernate will let you do all the CRUD operations. It will also call stored procedures, build queries so you aren’t always dragging the entire table back.

A simple query might be something like:

clip_image006

The funny bit here is that the “Id” thing is the Id property on my Product object. NHibernate will translate that to ProductID through the mapping file. I initially had some trouble with that, I was putting ProductID as the parameter because that is what the SQL where clause is going to use. NHibernate’s error message wasn’t very helpful for figuring this out, it took a few minutes of staring at the mapping file to see what was going on. It’s actually kind of cool.

I haven’t updated any of my objects and saved them back to the database. I’ve also not created a new record or deleted one. I’ll get to that stuff soon enough.

Wrap up

This should give you enough to get started using NHibernate. I’ll cover some more stuff as I go on. While I’m not agog at what it does, I’m lazy enough to just go with it. I could write a template to do my DAL the old way, but way? I already have a template that just needs some clean up? Also, DB stuff isn’t what gets me excited so why bother?

Where I really want to get to is using NHibernate for CSLA’s data access layer. There are plenty of templates for CSLA, so if I can get the two working together then I’ll really be smoking.

Published Wednesday, May 14, 2008 1:21 PM by jakew

Comments

No Comments

Anonymous comments are disabled