Click here to Skip to main content
13,736,490 members
Click here to Skip to main content
Add your own
alternative version


172 bookmarked
Posted 11 Nov 2004
Licenced CPOL

NHibernate in real world applications

, 11 Nov 2004
Rate this:
Please Sign up or sign in to vote.
How to use NHibernate in real world apps.

Example Application Screenshot


Hibernate has been huge in the Java world for being a easy to use high performance OR mapper, but only recently has it started to make a name for itself in the .NET world with NHibernate.

I've personally had a fair amount with different OR mappers, and object persistence frameworks. I decided to jump in and play with alpha .4 of NHibernate... and have honestly found it to be quite capable and relatively low on bugs (I haven't found any yet anyway).


After reading a couple of articles here (NHibernate) on the subject of NHibernate, I had a general clue, but probably more questions then answers.

I decided about bundling some real world examples along with explanation of why I am doing what, and it should be a pretty good starting point for anyone wanting to dive into OR Mappers, whether it be hobby or an enterprise application.

I'll start out first by saying, initially my work was based of these examples, however... I've found that the examples were sometimes incorrect, or files weren't named, or procedures weren't explained. Anyhow I aim to help with that!

Article Goals

This is my first submission of any kind, so keep non-constructive criticism to a minimum. I am 100% open to feedback, I don't claim to have all the answers, or claim to have the best methods to achieve this or that.

Over the next couple in a series of articles, I'd like to demonstrate n-tier frameworks utilizing NHibernate.

In this part, it'll be a basic data layer logic that I will be referencing directly for the time being, but in later articles, I intend to implement my business logic layer, as well as security on my business methods.

Target audience... anyone who is interested in N-Tier development. As I said before, it'll help hobbyists, and people interested in getting started in enterprise development. As well as, maybe fill in a little bit where I struggled (because of lack of documentation). I'd also like to provide a starting point for people who are just getting into building robust applications (whether for business or hobby... no excuse for bad application design).

Getting Started...

These steps are required, however, the order in which you do them is debatable.

Database Schema - I am using the Northwind database that is so standard, or downloadable from Microsoft. For now, I only really need Customers and Orders, the others are not necessary.

Northwind Schema

Class Definitions - You need to write a class with at least one constructor that has 0 parameters, and public properties representing data in the database: Bags, or Collections (Customer.Orders will end up being a IList after everything is said and done, we'll go into this a little more later...).


using System;
using System.Collections;

namespace nhibernator.BLL
    /// <SUMMARY>
    /// Summary description for Customer.
    /// </SUMMARY>
    public class Customer
        #region Private Internal Members
        private string m_CustomerID, m_CompanyName, m_ContactName, 
                m_Address, m_City, m_Region, m_PostalCode, m_Country;
        private IDictionary m_Orders;
        #region Public Properties

        public string CustomerID
                return m_CustomerID;
                m_CustomerID = value;


        public string CompanyName
                return m_CompanyName;
                m_CompanyName = value;

        public string ContactName
                return m_ContactName;
                m_ContactName = value;

        public string Address
                return m_Address;
                m_Address = value;
        public string City
                return m_City;
                m_City = value;

        public string Region
                return m_Region;
                m_Region = value;

        public string PostalCode
                return m_PostalCode;
                m_PostalCode = value;

        public string Country
                return m_Country;
                m_Country = value;
        public IDictionary Orders
                return m_Orders;
                m_Orders = value;

        public Customer()
            // TODO: Add constructor logic here

Ok, so now we have Customer class defined, we'll want to more or less duplicate this with Products, and orders.

Mapping file - <ClassName>.hbm.xml to be built as an embedded resource (defines how our Entities map to database objects).

You'll need one of these for each class you intend on persisting. Sounds time consuming, but comparing alternatives, it's relatively pain free.


<HIBERNATE-MAPPING" xmlns="urn:nhibernate-mapping-2.0">
    <CLASS name="nhibernator.BLL.Customer, nhibernator" table="Customers">

        <ID name="CustomerID" column="CustomerID" type="String" length="20"> 
            <GENERATOR class=assigned /> 
        <!-- Map properties I'd like to persist/fetch, 
            assume column = propery name, 
            and type is determined by reflection -->
        <property name="CompanyName"></property> 
        <property name="ContactName"></property> 
        <property name="Address"></property>
        <property name="City"></property>
        <property name="Region"></property>
        <property name="PostalCode"></property>
        <!-- Orders collection, pull customer orders but,
           loading lazy to minimize load time, resource usage. -->
        <SET name="Orders" cascade="all" lazy="true">
            <KEY column="CustomerID" />
            <ONE-TO-MANY class="nhibernator.BLL.Order, nhibernator" />

Unfortunately, Northwind has some questionable design practices. However, it's everywhere and thus I think it to be the perfect database for this example.

Normally, CustomerID, the ID field in Customer would be int or GUID, and unique int, and would have slightly different syntax. However, in this case it does not.

We can effectively "Alias" table field names to class properties like so:

<property name="CompName" column= "CompanyName" type="String" length="40"/>

However, I'd like to stick to database fields as much as possible. You can actually omit the column all together if you want the property to have the same name...

<property name="CompanyName" length="40"/>

You might also notice I've removed the type="string" bit of text. As of recent versions anyway NHibernate uses reflection to determine the type of the data (perhaps there are some performance ramifications, though really don't know).

Important note...

While you could probably load the mappings on the fly by specifying a filename, it seems to be a general practice to compile to embedded resource. Once you've created your .hbm.xml, make sure your build action is Embedded Resource like so:

build action

So now, I leave you to write the mapping files for the other two persisted objects, or you can simply download the code!

NHibernate configuration - can be done through XML file, resource stream, or manually in code. (I chose the code route, as trial and error with other methods never worked as they should; don't know if this is error on my part, or side effect of being an alpha).

NHibernate needs to be told what database provider to use, what SQL dialect to use, and connection string. Normally, a config file would look like this:

<?xml version="1.0" encoding="utf-8" ?>
<HIBERNATE-CONFIGURATION xmlns="urn:nhibernate-configuration-2.0">
    <SESSION-FACTORY name="nhibernator">
        <property name="connection.provider">
        <property name="connection.driver_class">
        <property name="connection.connection_string">
            Server=localhost;initial catalog=Northwind;Integrated Security=SSPI
        <property name="show_sql">false</property>
        <property name="dialect">
        <property name="use_outer_join">true</property>
        <property name="query.substitutions">
            true 1, false 0, yes 'Y', no 'N'
        <MAPPING assembly="nhibernator" />

However, like I said, I couldn't get the embedded resource stream for that to work, so I've written up the following code to simulate it. (Not as easy to come along and change later, but sufficient for getting the idea across).

In my data layer class CustomerFactory.cs, I have this code in the constructor for the time being:

config = new Configuration();
            IDictionary props = new Hashtable();

props["hibernate.connection.provider"] = 
props["hibernate.dialect" ] = "NHibernate.Dialect.MsSql2000Dialect"; 
props["hibernate.connection.driver_class"] = 
     "NHibernate.Driver.SqlClientDriver" ;
props["hibernate.connection.connection_string"] = 
     "Server=localhost;initial catalog=Northwind;Integrated Security=SSPI" ;

foreach( DictionaryEntry de in props ) 
    config.SetProperty( de.Key.ToString(), de.Value.ToString() );


*Log4Net configuration - sure you could skip this, but then good luck making sense of errors when things don't work =) In my client app, I simply read a log4net.config on load, and start from there.

n-Tiered Frameworks...

If you've encountered any sort of professional or enterprise software development, you've undoubtedly had these concepts beaten into your brain, and probably for the good.

Too much abstraction is bad, but a decent separation of data, business logic, and presentation logic can improve efficiency, code readability, and general upkeep.

So I've created a root namespace, and then created DLL for data layer logic (sure I could have used something a little more informative, but I am a creature of habit).

A subnamespace (?) of BLL for business layer logic...

And finally a whole other project for my presentation logic (I like to know I can use my tiered logic in console, web, remoting, webservices etc.).

DataLayerLogic - By definition, this code really should probably handle getting/updating/inserting/deleting entities in the database as well as data validation (SQL injection proofing etc.)

Luckily, NHibernate handles a fair amount of what's supposed to be done in the data layer itself, and so we generally end up writing some minor data validation, and methods to fetch all, fetch a single entity, or fetch entities based on some criteria.

What I've done is create a separate "factory" for each entity type (CustomerFactory, ProductFactory, OrderFactory). In the constructor, I set up the NHibernate session factory, and spawn a NHibernate isession. Then each method to set/get data checks to see session.IsConnected, and if it's not session.ReConnect(). This is important as data isn't blocked the entire time my data factory is instantiated. I perform the logic, and then disconnect. On dispose of my factory class, I make sure session gets disposed etc.

I've got two methods built out for fetching customers in CustomerFactory.cs.

First... GetCustomers() in which I simply get back an IList of Customer objects.

Secondly... GetCustomer(string CustomerID) in which I feed it an ID such as "BERGS", and since I fetch with FETCHMODE.EAGER flag, I get all the subcollections, without trying to access them.

BusinessLayerLogic - Theoretically, in a lot of cases, simply wrapping DataLayerLogic methods/classes is sufficient. However I end to fire off events, and do extra validation that wouldn't be simple insertion problems.

In this article, I've not really built out this layer; look for it in the next in this series.

PresentationLogic - in this case, I simply create an instance of my DataLayerLogic, or invoke some of the static methods, and update user interface appropriately. (One could use ASP.NET or WinForms, or upcoming XAML or any number of presentation methods here).

I was sort of in a rush in this case; however, my little WinForms app will fetch all customers, and insert hard-coded data as a new user. (I'll make this a lot more presentable in an update to this article.)

Of course, your namespace structure could look totally different (as most people have <companyname>.<technology>.<project>.<feature>), but for all intent and purposes, I've come up with this:

namespace layout

Notice the .hbm.xmls. You can actually throw these in a mappings folder or whatever makes things cleaner for you...

I can simply call a static method and get a collection of Customers which are data-bindable by default.

Where to go from here?

Nhibernate has a wealth of different configuration options for caching and performance tweaking, which I will get into in my second article. Unfortunately, there isn't a whole lot of documentation on the subject, so you can try looking at hibernate documentation.

Also in the next article, you can expect to see a mechanism for my n-tier BusinessLayerLogic to check credentials for fetching the data.

In closing...

Like I said, I struggled with NHibernate. Getting it up and running the first time can be quite a pain; however, it can be done. The example works, but you'll probably want to download NHibernate separately from here and add nhibernate.dll to your "References".

Again, please leave constructive criticism only. This is my first article, and I realize it was on a broad subject. Thanks, and keep your eyes open for part 2!


v1 - First version of the article. No bugging me about layout, I'm working on it. Documentation too!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United States United States
I've been involved with software development since teaching Basic to teachers in 6th grade. Since then I've been involved with every aspect of computers.

Lately, I've involved myself very much in building Entperise Java and .Net applications.

You may also be interested in...


Comments and Discussions

Questionwhich database used? Pin
Aarti Meswania20-Feb-13 0:40
memberAarti Meswania20-Feb-13 0:40 
GeneralMy vote of 4 Pin
yasar.facebook23-Nov-10 5:36
memberyasar.facebook23-Nov-10 5:36 
Questionhow to save an xml( an embedded resource) in project? Pin
Tarun.K.S12-Oct-10 0:26
memberTarun.K.S12-Oct-10 0:26 
Generalplease help me in simple nhibernate project Pin
saeedmain22-Aug-10 4:06
membersaeedmain22-Aug-10 4:06 
GeneralRe: please help me in simple nhibernate project Pin
jseee_7-Sep-10 21:56
memberjseee_7-Sep-10 21:56 
GeneralNeed for help Pin
a_kiani24-Oct-09 22:37
membera_kiani24-Oct-09 22:37 
GeneralPlease answer Pin
Vikas Misra(TCS)12-Oct-09 5:12
memberVikas Misra(TCS)12-Oct-09 5:12 
Generalrename your classes Pin
Dean Hiller24-May-08 20:55
memberDean Hiller24-May-08 20:55 
Generalproblems with zip file Pin
Dean Hiller24-May-08 20:53
memberDean Hiller24-May-08 20:53 
QuestionHow to update primary key value (customerid value) Pin
lpbinh9-Mar-08 21:12
memberlpbinh9-Mar-08 21:12 
GeneralCustomerFactory vs. CustomerRepository Pin
Özgür3-Nov-07 23:07
memberÖzgür3-Nov-07 23:07 
GeneralCommunication between BLL and DAL Pin
Vimalsoft(Pty) Ltd2-Oct-07 4:27
memberVimalsoft(Pty) Ltd2-Oct-07 4:27 
GeneralEasy mapping (without the codegen) Pin
awesomeo11-Sep-07 19:57
memberawesomeo11-Sep-07 19:57 
General Pin
Gary Brewer25-Jun-07 12:05
memberGary Brewer25-Jun-07 12:05 
QuestionSaveOrUpdate() Pin
CoderByHeart7-May-07 1:13
memberCoderByHeart7-May-07 1:13 
AnswerRe: SaveOrUpdate() Pin
jokiz10-May-07 20:48
memberjokiz10-May-07 20:48 
GeneralRe: SaveOrUpdate() Pin
CoderByHeart15-May-07 1:48
memberCoderByHeart15-May-07 1:48 
Generalhbm2ddl Pin
Edwill Leighton12-Apr-07 12:40
memberEdwill Leighton12-Apr-07 12:40 
GeneralRe: hbm2ddl [modified] Pin
Dennis Decoene30-Jul-07 21:28
memberDennis Decoene30-Jul-07 21:28 
GeneralMessage Closed Pin
18-Mar-07 23:50
memberIqbal M Khan18-Mar-07 23:50 
GeneralRe: Useful option Pin
ronnyek19-Mar-07 3:28
memberronnyek19-Mar-07 3:28 
GeneralCould not save object..what's happen about NHibernate ? [modified] Pin
tkimji28-Feb-07 23:02
membertkimji28-Feb-07 23:02 
GeneralAlternative to Persistance Mappers Pin
Xin Zhao13-Feb-07 13:36
memberXin Zhao13-Feb-07 13:36 
GeneralRe: Alternative to Persistance Mappers Pin
ronnyek13-Feb-07 14:29
memberronnyek13-Feb-07 14:29 
GeneralRe: Alternative to Persistance Mappers Pin
Xin Zhao27-Feb-07 1:38
memberXin Zhao27-Feb-07 1:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180920.1 | Last Updated 12 Nov 2004
Article Copyright 2004 by ronnyek
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid