Progressing towards Innovation...


An Introduction to NHibernate Queries

July 1, 2014by GLBADMIN29

Hi, I am Abhay Kumar. I am a .NET developer at Globussoft with about 2 years of experience. I would share few things about NHibernate with its advantages and disadvantages.

NHibernate: ORM (Object-Relational-Mapping)

NHibernate’s primary feature is mapping from .NET classes to database tables (and from CLR data types to SQL data types). NHibernate also provides data query and retrieval facilities.

NHibernate, an open-source framework, is an object/relational mapping (ORM) application for .NET environments. It 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 table and a class 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.

There are two types of binding:

  • Loosely typed binding
  • Strongly typed binding


Loosely typed binding:

It writes mappings in XML (.hbm, .xml ) files. It defines all relationships in this file as shown in figure below:

Strongly typed binding (Fluent NHibernate):

Strongly typed binding (Fluent NHibernate):Fluent NHibernate offers an alternative to NHibernate’s standard XML mapping files. Rather than writing XML documents (.hbm, .xml files), Fluent NHibernate lets you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.

Fluent NHibernate also has several other tools, including:

  • Auto mappings – where mappings are inferred from the design of your entities
  • Persistence specification testing – round-trip testing for your entities, without ever having to write a line of CRUD
  • Full application configuration – with Fluent configuration API
  • Database configuration – fluently configure your database in code


Sample Queries using NHibernate

public static void Add(Domain.Admin user)
    //Creates a database connection and opens up a session
    using (NHibernate.ISession session = SessionFactory.GetNewSession())
        //After Session creation, start and open Transaction.
        using (NHibernate.ITransaction transaction = session.BeginTransaction())
            //Proceed action to save data.
        }//End Using trasaction
    }//End Using session

public static void Update(Domain.Admin user)
    //Creates a database connection and opens up a session
    using (NHibernate.ISession session = SessionFactory.GetNewSession())
        //After Session creation, start Transaction.
        using (NHibernate.ITransaction transaction = session.BeginTransaction())
                // Proceed Sction to update Data.
                // And Set the reuired paremeters to find the specific values.
                int i = session.CreateQuery("Update Admin set Image =:profileurl, UserName =: username , TimeZone=:timezone,FirstName =:first,LastName =:last  where Id = :twtuserid")
                               .SetParameter("twtuserid", user.Id)
                               .SetParameter("profileurl", user.Image)
                               .SetParameter("username", user.UserName)
                               .SetParameter("timezone", user.TimeZone)
            catch (Exception ex)
        }//End Using trasaction
    }//End Using session

The benefits of NHibernate ORM

  • Productivity

Eliminates lots of repetitive code – focus on business logic
Database schema is generated automatically

  • Maintainability

Fewer lines of code – easier to understand
Easier to manage change in the object model

  • Performance

Lazy loading – associations are fetched when needed

Nhibernate in a Nutshell

  • ISessionFactory

One per database (or application)
Expensive to create

  • ISession

Portal to the database
Saves, retrieves

  • ITransaction

Encapsulates database transaction

Advantages of NHibernate

  • Full ORM framework.
  • NHibernate database structure provides a more complete package, it will map a database schema more complete object model supports encapsulation, continue mechanism, more powerful than the average ORM flexibility
  • Developers can manipulate the database in full accordance with the object model
  • Code is automatically generated, to reduce the amount of code and sql development, enables developers to from open sql ADO.NET and affairs cache underlying
  • Reduced development effort
  • Better document support


Limitations of NHibernate

  • Increased startup time due to metadata preparation ( not good for desktop like apps)
  • Huge learning curve without ORM background
  • Comparatively Hard to fine tune generated sql

So we see here that NHibernate is a good ORM for mapping objects in your OO application to tables in a database for persistence.

It saves us from writing a lot of tedious ADO.NET code while also boosting the developer productivity when developing CRUD applications, that is, applications whose main purpose is to Create, Read, Update, and Delete data in a database.