Translate

Sunday, October 7, 2012

nhibernate tutorial for beginners with a super simple example ( Nhibernate with Linq )


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

Professor prof1 = new Professor { firstName = "Julia", lastName = "Roberts" };
session.Save(prof1);

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)
using (ITransaction transaction = session.BeginTransaction())
                {
                    var prof = session.QueryOver<Professor>().Where(x => x.firstName == "Sam").SingleOrDefault();
                    prof.lastName = "Stallone";
                    transaction.Commit();
                }

                    

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.

  • 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LearnNHibernate
{
    class Professor
    {
        public virtual int professorID { getset; }
        public virtual string firstName { getset; }
        public virtual string lastName { getset; }

    }


}


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.

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();
                }

            }

        }



    }
}


At this point this is how the app looks like in my Visual studio.




















Now you can go ahead and run the app.

 This is how a select on that table looks like after you have run this app




















Some helpful resources

NHibernate Mapping Generator

8 comments:

  1. The app.config file, what type of file is it? and where do I put it?

    ReplyDelete
    Replies
    1. Diego,
      The 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.

      Delete
  2. 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.)

    ReplyDelete
  3. Very good example to get started on. Just what I've been lookiing for. Nice job. Thanks for sharing!

    ReplyDelete
  4. Very nice article! Exactly what a beginner would like to see...

    ReplyDelete
  5. Excellent and right to the point. More than enough to get my hands "dirty"!

    ReplyDelete
  6. awesome. i realy feel relax

    ReplyDelete
  7. really simple, thanks a lot

    ReplyDelete

Comments will appear once they have been approved by the moderator