What is NHibernate?
An ORM tool called Hibernate that has been around since 2001, was immensely popular in the Java world . Since Hibernate was so hugely popular it was decided that .net should have access to this tool too. That's why a .net version of Hibernate called NHibernate was created.
Nhibernate is a set of dlls that serve as your persistence (data access) layer. The way it works is you create a mapping (using an xml file) between the database tables and classes in your application. Once the mapping is set up, you can just modify an instance of the class and let nhibernate generate the SQL statements for you.
For example if I create a mapping between a professor class and a professor table, I could do something like
to save a new professor to the database.
Or do this to update an existing record (update last name to Stallone where first name is Sam)
That simple.
What are the benefits of using NHibernate?
Besides the fact that once you learn nhibernate, you will save a lot of time not having to write all that code for the data access layer, there are other benefits too.
How to use NHibernate?
I will create an application that manipulates a table called professors in a SQL server 2008 database HelloNhibernate.
This is how a select on that table looks like.
The column professorID is set as an Identity.
In this example I will use NHibernate to
To follow the tutorial first download the NHibernate version 3.3.1. Then follow the steps below
1>Create a console application called ConsoleApplication1 and add a reference to these two dlls that you get in the download above
Iesi.Collections
NHibernate
Set the Copy local property for these two dlls to true.
using System;
3>Add an XML file for mapping called Professor.hbm.xml (the .hbm is what tells the application that this is an nhibernate mapping file). This file maps columns on the table [HelloNhibernate].[dbo].[professors] to the class Professor.
This is how a select on that table looks like after you have run this app
Some helpful resources
NHibernate Mapping Generator
An ORM tool called Hibernate that has been around since 2001, was immensely popular in the Java world . Since Hibernate was so hugely popular it was decided that .net should have access to this tool too. That's why a .net version of Hibernate called NHibernate was created.
Nhibernate is a set of dlls that serve as your persistence (data access) layer. The way it works is you create a mapping (using an xml file) between the database tables and classes in your application. Once the mapping is set up, you can just modify an instance of the class and let nhibernate generate the SQL statements for you.
For example if I create a mapping between a professor class and a professor table, I could do something like
Professor prof1 = new
Professor { firstName = "Julia", lastName = "Roberts" };
session.Save(prof1);
using (ITransaction transaction = session.BeginTransaction())
{
var prof = session.QueryOver<Professor>().Where(x => x.firstName == "Sam").SingleOrDefault();
prof.lastName = "Stallone";
transaction.Commit();
}
Besides the fact that once you learn nhibernate, you will save a lot of time not having to write all that code for the data access layer, there are other benefits too.
- NHibernate is a very mature tool. (Hibernate came into existence in 2001)
- Among other things it takes care of SQL injection and database concurrency for you.
- If you want to switch from SQL to Oracle, the application code doesn't have to change.(NHibernate supports many database management systems)
- NHibernate is opensource.
How to use NHibernate?
I will create an application that manipulates a table called professors in a SQL server 2008 database HelloNhibernate.
This is how a select on that table looks like.
The column professorID is set as an Identity.
In this example I will use NHibernate to
- Query the record where first name is Sam (Read)
- Update Sam's last name to Stallone (Update)
- Add a new professor Julia Roberts (Create)
- Delete Steve Balmer (Delete)
To follow the tutorial first download the NHibernate version 3.3.1. Then follow the steps below
1>Create a console application called ConsoleApplication1 and add a reference to these two dlls that you get in the download above
Iesi.Collections
NHibernate
Set the Copy local property for these two dlls to true.
2>Add the class that corresponds to the professors table in the database
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LearnNHibernate
{
class Professor
{
public virtual int professorID { get; set; }
public virtual string firstName { get; set; }
public virtual string lastName { get; set; }
}
}
3>Add an XML file for mapping called Professor.hbm.xml (the .hbm is what tells the application that this is an nhibernate mapping file). This file maps columns on the table [HelloNhibernate].[dbo].[professors] to the class Professor.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="ConsoleApplication1"
namespace="LearnNHibernate">
<class name="Professor" table="professors">
<id column="professorID" name="professorID" type="int">
<generator class="identity"/>
</id>
<property column="firstName" name="firstName" />
<property column="lastName" name="lastName" />
</class>
</hibernate-mapping>
The property build action of this xml file should be set as Embedded Resource. If you don't do that, no error would be thrown but then no data would be fetched from the database either.
The assembly and namespace in the <hibernate-mapping> element is the assembly and namespace of the class that is listed in the mapping file.
The assembly and namespace in the <hibernate-mapping> element is the assembly and namespace of the class that is listed in the mapping file.
4>Add an app.config to your application. Just update the connection string in the config below.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration"
type="NHibernate.Cfg.ConfigurationSectionHandler,
NHibernate"/>
</configSections>
<connectionStrings>
<add name="db" connectionString="Server=yourServerName;Database=HelloNhibernate;
Trusted_Connection=SSPI"/>
</connectionStrings>
<hibernate-configuration
xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="dialect">
NHibernate.Dialect.MsSql2008Dialect,
NHibernate
</property>
<property name="connection.connection_string_name">
db
</property>
</session-factory>
</hibernate-configuration>
</configuration>
5>Copy paste this into your program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace LearnNHibernate
{
class Program
{
static void Main(string[] args)
{
//***** Configure Nhibernate ******************
var nhConfig = new Configuration().Configure();
nhConfig.AddAssembly(typeof(Professor).Assembly);
//Name of the assembly that contains the mapping file. If mapping file is in the current assembly , then use nhConfig.AddAssembly(Assembly.GetExecutingAssembly());
var sessionFactory = nhConfig.BuildSessionFactory();
//*********************************************
//***** Read ******************************
//Print the last name of the professor named Sam
using (ISession session = sessionFactory.OpenSession())
{
var prof = session.QueryOver<Professor>().Where(x => x.firstName == "Sam").SingleOrDefault();
Console.WriteLine(prof.lastName);
}
//*********************************************
//***** Update ******************************
//Update Sam's last name to Stallone
using (ISession
session = sessionFactory.OpenSession())
{
using (ITransaction
transaction = session.BeginTransaction())
{
var prof = session.QueryOver<Professor>().Where(x => x.firstName == "Sam").SingleOrDefault();
prof.lastName = "Stallone";
transaction.Commit();
}
}
//*********************************************
//***** Add ******************************
//Insert a professor named Julia Roberts
Professor prof1 = new
Professor { firstName = "Julia", lastName = "Roberts" };
using (ISession
session = sessionFactory.OpenSession())
{
using (ITransaction
transaction = session.BeginTransaction())
{
session.Save(prof1);
transaction.Commit();
}
}
Console.ReadKey();
//*********************************************
//***** Delete ******************************
//Delete the professor named Steve
using (ISession
session = sessionFactory.OpenSession())
{
var delProf = session.QueryOver<Professor>().Where(x => x.firstName == "Steve").SingleOrDefault();
using (ITransaction
transaction = session.BeginTransaction())
{
session.Delete(delProf);
transaction.Commit();
}
}
}
}
}
Now you can go ahead and run the app.
Some helpful resources
NHibernate Mapping Generator
The app.config file, what type of file is it? and where do I put it?
ReplyDeleteDiego,
DeleteThe App.config is a regular config file. I have updated the article with a snapshot of the Visual studio project. See if that helps you.
Thanks so much for this simple explanation - its the best I found for a complete nHibernate newbie. (Personally I prefer LLBLGEN as I'm a data-centric guy rather than class centric.)
ReplyDeleteVery good example to get started on. Just what I've been lookiing for. Nice job. Thanks for sharing!
ReplyDeleteVery nice article! Exactly what a beginner would like to see...
ReplyDeleteExcellent and right to the point. More than enough to get my hands "dirty"!
ReplyDeleteawesome. i realy feel relax
ReplyDeletereally simple, thanks a lot
ReplyDelete