Nhibernate for Database Independency with example

Hibernate is a persistence engine in the form of a Framework. It loads business objects from a database and saves changes from those objects back to the database. As we mentioned above, it can load or save an entire object graph with just a line or two of code. NHibernate uses mapping files to guide its translation from the database to business objects and back again. As an alternative, you can use attributes on classes and properties, instead of mapping files.

NHibernate Download Location : http://sourceforge.net/projects/nhibernate/

In this example I am using SQL SERVER 2008.


Create Table Query :

create table ACCOUNT (
ACCID int identity(1,1) not null,
USERNAME varchar(50) null,
PASS varchar(50) null,
constraint PK_ACCOUNT primary key nonclustered (ACCID)

Next step, we will create simple solution in Visual Studio 2008 SP1 (remember … to connect to SQL Server 2008, your Visual Studio 2008 must be Service Pack 1 ).

Add some references

NHibernate.dll (NHibernate library)
NHibernate.ByteCode.LinFu.dll (for lazy loading)

Now test your connection with database using Server Explorer and get the connection string from server explorer.

For my example, my database connection string is :

Data Source=WIRTH;Initial Catalog=TestNHibernate;User ID=azer89;Password=azer89

Then create an App.config file in your project.
Set your App.config like this :

<?xml version="1.0" encoding="utf-8" ?>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=WIRTH;Initial Catalog=TestNHibernate;User ID=azer89;Password=azer89</property>
<property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
<mapping assembly="NHibernateTest"/>

You must pay attention in property connection.connection_string and dialect in code above. Add a model class similar to Account Table, its fields must be similar too

Your Account.cs should be like this :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NHibernateTest
class Account
private int accId;
private string username;
private string pass;

public virtual int AccId
get { return accId; }
set { accId = value; }

public virtual string UserName
get { return username; }
set { username = value; }

public virtual string Pass
get { return pass; }
set { pass = value; }

After creating Account class, we will create map to Account Table using XML file, so NHibernate will know that Account class in application will map to Account Table in database. The XML filename will be "Account.nbm.xml"

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernateTest" assembly="NHibernateTest">
<class name="Account" table="ACCOUNT" lazy="false">
<id name="AccId">
<column name="ACCID"/>
<generator class="native"/>
<property name="UserName">
<column name="username"/>
<property name="Pass">
<column name="pass"/>

Look at generator class, its value is "native", it is because we have set ACCID column into autoincrement. Oh yeah, Build Action for hbm.xml file must be "Embedded Resource"

Next step is to create persistence class, we will name it NHibernateHelper.cs

using System.Reflection;
using NHibernate;
using NHibernate.Cfg;

namespace NHibernateTest
public sealed class NHibernateHelper
private static ISessionFactory SessionFactory;

private static void OpenSession()
Configuration configuration = new Configuration();
SessionFactory = configuration.BuildSessionFactory();

public static ISession GetCurrentSession()
if (SessionFactory == null)

return SessionFactory.OpenSession();

public static void CloseSessionFactory()
if (SessionFactory != null)

Since ISessionFactory is expensive to create (it almost take one second in my computer !!!) we will create one object of ISessionFactory, otherwise with ISession, it is very cheap to create, so we can create it very ofter in your application. We will test the code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;

namespace NHibernateTest
class Program
static void Main(string[] args)
string username = "reza";
string pass = "reza";

ISession session = NHibernateHelper.GetCurrentSession();
IQuery query = session.CreateQuery("FROM Account WHERE username = :name AND pass = :pass ");
query.SetString("name", username);
query.SetString("pass", pass);
IList acc = query.List();
if (acc.Count == 0)
Console.WriteLine("Cannot find specified user");
Console.WriteLine("Found " + acc[0].UserName);




No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: