Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / SQL

NHibernate Basics

Rate me:
Please Sign up or sign in to vote.
4.73/5 (31 votes)
10 Jul 2011CPOL3 min read 136K   5.3K   44   33
ABCs of NHibernate, a small application to demonstrate save and load of objects to and from Database.
Demo Application UI

Introduction

NHibernate is an Object-Relational Mapping (ORM) solution for the .NET Platform. It provides a framework for mapping an object oriented domain model to a traditional relational database. It's primary feature is mapping from .NET classes to database tables and from CLR data types to SQL data types.

As the title of this article, we are going to see this feature only; How it loads business object from a database and saves changes from these objects back to the database.

Background

The demo application demonstrates in simple possible way how to setup and use NHibernate. The application creates an Employee object and stores it in a Employee table. It also does some operations like retrieval and deletion of Employee objects, etc. The application is created with NHibernate 3.2.0, VS 2010 and SQL Server 2008.

Using the Code

Database

Here we are going to setup the database first. Use SQL Server Management Studio to create a database that can be used to elaborate with. As shown below, create a new database named NHibernateBasics.

Create New Database

Then add a table called Employee with two columns; ID and Name.

Create New Table

ID shall be the primary key and used as identity. Don’t forget to enable Identity Specification in the properties.

Set Table Properties

Business Object

The database is ready for the demonstration. Now start Visual Studio and create a new WindowsFormsApplication project called NHibernateBasics. Add a new class called Employee.cs with the following code:

C#
namespace NHibernateBasics
{
    public class Employee
    {
        public virtual int ID { get; set; }

        public virtual string Name { get; set; }
    }
}

One of NHibernate's strongest features is that it doesn't need special interfaces on business classes. These objects are not aware of the mechanism used to load and save them. However it requires the properties declared as virtual so that it can create proxies as needed.

Mapping XML File

In the absence of specific code for hibernation, someone should guide the translation from the database to business object and back again. This can be achieved through either mapping XML file or by applying attributes on classes and properties. In the demo application, we have used mapping file to keep our business object class clean.

Add a new XML file to the project. The XML file will be used as the mapping file. The name of the file must be Employee.hbm.xml. Both class <name>.cs file and mapping <name>.hbm.xml file should be in same folder and <name> should be same. Add the following content to the file:

XML
 <?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
	namespace="NHibernateBasics" assembly="NHibernateBasics">
  <class name="Employee" table="Employee">
    <id name="ID" column="ID">
      <generator class="identity"/>
    </id>
    <property name="Name" column="Name"  />
  </class>
</hibernate-mapping>

In the properties for the mapping XML file, set build action to Embedded Resource.

Set Mapping File Properties

Configuration

Add a new application configuration file (app.config). Copy the following content:

XML
 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" 
	type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">
	NHibernate.Connection.DriverConnectionProvider</property>
      <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
      <property name="query.substitutions">hqlFunction=SQLFUNC</property>
      <property name="connection.driver_class">
	NHibernate.Driver.SqlClientDriver</property>
      <property name="connection.connection_string">
	Data Source=(Local)\SQL2008;Initial Catalog=NHibernateBasics;
	Integrated Security=True</property>
      <property name="show_sql">true</property>
      <mapping assembly="NHibernateBasics" />
    </session-factory>
  </hibernate-configuration>
</configuration>

Adjust the connection.connection_string property so that it works for your database. Set Catalog=<Database Name>; here it is NHibernateBasics. Set mapping assembly=<Class DLL Name>; here it is again NHibernateBasics.

Demonstration

Now we are almost ready for the demonstration. We just need to access the business class objects and perform certain operations on it.

Save

C#
using(mySession.BeginTransaction())
{
    // Insert two employees in Database
    mySession.Save(myInitialObjects[0]); 
    mySession.Save(myInitialObjects[1]); 
    mySession.Transaction.Commit(); 
} 

Load

C#
using(mySession.BeginTransaction())
{
    // Create the criteria and load data
    ICriteria criteria = mySession.CreateCriteria<employee>();
    IList<employee> list = criteria.List<employee>();
    for (int i = 0; i < myFinalObjects.Length; i++)
    {
        myFinalObjects[i] = list[i];
        MessageBox.Show("ID: " + myFinalObjects[i].ID + " 
			Name: " + myFinalObjects[i].Name);
    }
    mySession.Transaction.Commit();
 }

Compare

C#
StringBuilder messageString = new StringBuilder();
// Compare both objects
for (int i = 0; i < 2; i++)
{
    messageString.AppendLine("Comparing Class Object " + 
	myInitialObjects[i].Name + " and DB Object " + 
	myFinalObjects[i].Name + ". Result = " + 
	myInitialObjects[i].Equals(myFinalObjects[i]).ToString());
}
MessageBox.Show(messageString.ToString());

Delete

C#
using (mySession.BeginTransaction())
{
    // Delete one object from Database
    mySession.Delete(myInitialObjects[0]);
    mySession.Transaction.Commit();
}

Display

C#
using (mySession.BeginTransaction())
{
     ICriteria criteria = mySession.CreateCriteria<employee>();
     IList<employee> list = criteria.List<employee>();
     StringBuilder messageString = new StringBuilder();
     // Load and display the data
     foreach (Employee employee in list)
     {
         messageString.AppendLine("ID: " + employee.ID + " Name: " + employee.Name);
     }
     MessageBox.Show(messageString.ToString());
}

NHibernate guarantees that two object references will point to the same object only if the references are set in the same session. If we save the objects in one session and load them in different sessions, then both the objects will be different objects.

Hope it will help you to understand the basics of NHibernate. Happy coding! :)

Points of Interest

Although there are many articles available for NHibernate, target audience for this article are those who just started learning NHibernate, including me :). Another nice article with more information is available here.

History

  • 07/07/2011 - Initial post

License

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


Written By
Architect Philips
India India
Have been working with computers since the early 00's. Since then I've been building, fixing, configuring, installing, coding and designing with them. At present I mainly code windows applications in C#, WCF, WPF and SQL. I'm very interested in Design Patterns and try and use these generic principles in all new projects to create truly n-tier architectures. Also I like to code for making the User Interface very attractive...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 250201316-Jul-11 3:52
Member 250201316-Jul-11 3:52 
QuestionRollback() not seen in your code Pin
Herman<T>.Instance11-Jul-11 22:56
Herman<T>.Instance11-Jul-11 22:56 
AnswerRe: Rollback() not seen in your code Pin
Kumar, Ravikant12-Jul-11 17:29
Kumar, Ravikant12-Jul-11 17:29 
GeneralRe: Rollback() not seen in your code Pin
Herman<T>.Instance12-Jul-11 22:41
Herman<T>.Instance12-Jul-11 22:41 
GeneralRe: Rollback() not seen in your code Pin
Kumar, Ravikant12-Jul-11 23:11
Kumar, Ravikant12-Jul-11 23:11 
GeneralRe: Rollback() not seen in your code Pin
NYCChris19-Jul-11 7:51
NYCChris19-Jul-11 7:51 
GeneralRe: Rollback() not seen in your code Pin
Herman<T>.Instance19-Jul-11 21:36
Herman<T>.Instance19-Jul-11 21:36 
GeneralRe: Rollback() not seen in your code Pin
NYCChris20-Jul-11 7:02
NYCChris20-Jul-11 7:02 
Thank you for your reply! Ayende is usually pretty good about database knowledge, so before I accepted a bad guru as the answer, I had to go research this further. Let me explain what I have learned by address your points.

1. 'Not everything in a db is done in a transaction'
In SQL Server every connection defaults to Autocommit mode.[^]

The first paragraph from the article:
"Autocommit mode is the default transaction management mode of the SQL Server Database Engine. Every Transact-SQL statement is committed or rolled back when it completes. If a statement completes successfully, it is committed; if it encounters any error, it is rolled back. A connection to an instance of the Database Engine operates in autocommit mode whenever this default mode has not been overridden by either explicit or implicit transactions. Autocommit mode is also the default mode for ADO, OLE DB, ODBC, and DB-Library."

So unless you set Implicit Transactions ON or you explicitly create a transaction, every statement is rolled into it's own transaction. Again I cannot speak to other databases, such as Oracle, or Postgress, etc... but I would think that most modern database servers share a common level of features. Perhaps autocommit is a common feature to these other databases?

2. 'Consistency has not much to do with transactions.'
I think perhaps you misunderstood me here. Let me explain with an example. If 2 transactions are running, the first being a SELECT and the second containing a DELETE/INSERT/UPDATE statement, what should happen to your SELECT? According to the SQL Server docs, transactions run in READ COMMITTED isolation mode by default. Here is a link that explains more about Isolation Levels.[^]

So if you do nothing at all, AUTOCOMMIT guarantees that you are running within a transaction, and READ COMMITTED can lead to non repeatable reads. And this might be ok, but by explicitly declaring the transaction, you get to control how the SELECT data is returned. If you are coming back with large results sets, you can set a different isolation level, for example READ UNCOMMITTED to avoid locks.

3. 'Since ORM only maps objects it has less knowlegde of the databasemodel, contraints and foreign keys.'
My admittedly limited knowledge of NHibernate disputs this. For example, there is a feature in NHibernate that lets you create the database creation plan from its mappings. Whenever I have done this I find that NHibernate creates the tables WITH foreign key constraints, primary key constraints etc. It knows how to do this by how well you setup the mapping files. In particular the way you setup your collection cascade settings. Also you can explicitly tell it to use a specific foreign key as well.

Now going slightly off topic
I've successfully used NHibernate in a number of projects over the years, and I have come to appreciate it for what it is. Unfortunately it is not the easiest tool to learn, and I am the first to admit that it has more than it's share of 'quirks. The hbm mapping files are a bit arcane and hard to master. I still struggle with them. And the original CreateCriteria syntax was also more difficult to use than I would have liked.

It is NOT the tool you want when you need to do bulk manipulation of data. But for your standard CRUD applications I find it works very well. It also greatly helps me in unit testing. I honestly would not know how to begin testing a pure database/stored procedure model. With NHibernate I can create create an in-memory copy of a sqlite db automatically, based on the mappings. Populate it with some dummy data, and I can test away happily.

FYI: I do heartily recommend FluentNHibernate over hbm files any day! And as of 3.0 I use the NHibnernate-LINQ bridge for querying exclusively and love it.
GeneralRe: Rollback() not seen in your code Pin
Kumar, Ravikant20-Jul-11 18:04
Kumar, Ravikant20-Jul-11 18:04 
QuestionGood articel Pin
Devart11-Jul-11 21:31
Devart11-Jul-11 21:31 
GeneralMy vote of 5 Pin
Rhuros10-Jul-11 23:39
professionalRhuros10-Jul-11 23:39 

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.