You are on page 1of 12

NHibernate is an open source Object-Relational Mapper (ORM) framework for .Net languages.

NHibernate can be used to treat database relational tables as if they are objects. What this
means is we can have a class representing an object with its properties. The class objected can
be used to save and retrieve data from the database without manually writing the SQL
statements. 

Advantages of NHibernate ORM framework


1. Reduced Development Time – how? That is a good question; NHibernate generates
the queries for you. This saves you time spent writing your own database queries.
2. Improved Security – NHibernate will handle the sanitization of the database input
parameters for you. This means you have some base protection against SQL Injection.
However, Un-parameterized Hibernate Query Language (HQL) is vulnerability to SQL
Injection
3. Multiple DBMS support – all it takes to switch from one database engine such as MS
SQL Server to MySQL is updating the configuration file.
4. Established community – this means most of the challenges you will face have already
been solved by others and the solutions are available online
In addition to the above advantages, NHibernate also provides First and Second Level Caching
for optimization system performance. The system is also open source, this means you can
develop on top of it if need be.
NHibernate C# Example
We will design the following simple application for managing customer
records. 

 Crea
te a new project and name it CustomerRecords Rename Form1.cs to frmCustomers Design the
above graphical user interface and set the properties for the controls as follows
S/N CONTROL PROPERTY VALUE
1 FORM Name frmCustomers
2 FORM Text Customer Records
3 DataGridView Name dgvCustomers
4 Label Text Customer ID
5 TextBox Name txtCustomerID
6 Button Name txtClear
7 Button Text Clear
8 Button Name txtAddNew
9 Button Text Add New
10 Button Name txtUpdate
11 Button Text Update
12 Button Name txtDelete
13 Button Text Delete
14 Label Text Customer Name
15 TextBox Name txtName
16 Label Text Email
17 TextBox Name txtEmail
18 Label Text Contact Person
19 TextBox Name txtContactPerson
20 Label Text Contact Number
21 TextBox Name txtContactNumber
22 Label Text Physical Address
23 TextBox Name txtPhysicalAddress
24 Label Text Postal Address
25 TextBox Name txtPostalAddress
  Add a new class and name it Customers.cs Add a new XML file and name it
Customers.hbm.xml Your project structure should now look as

follows 
NHibernate References
Download NHibernate from this link. Unzip the contents of the download. Right click on
references from the solution explorer Browse to the folder where you unzipped the files you
downloaded Browse to the Required_Bins directory. It has two dll files lesi.Collections.dll and
NHibernate.dll Add both files as shown in the image
below 
 Cl
ick on OK button when done
NHibernate Class
The Customers class will represent the customer object. We will now create properties in the
customer class that will match the fields in the database. Add the following code to Customers.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CustomerRecords
{
class Customers
{
public virtual int customer_id { get; set; }
public virtual string name { get; set; }
public virtual string email { get; set; }
public virtual string contact_person { get; set; }
public virtual string postal_address { get; set; }
public virtual string physical_address { get; set; }
public virtual string contact_number { get; set; }
}
}
HERE,
 “public virtual int property { get; set; }” sets a class property that matches a field in
the database. Note the property is defined with a virtual keyword. This makes it possible
for the fields to be overridden.
NHibernate Mapping
NHibernate uses XML files for mapping database fields to objects properties. The XML file
should always end with *.hbm.xml extension. Open the file Customers.hbm.xml Add the following
code
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="CustomerRecords" namespace="CustomerRecords">
<class name="Customers">
<id name="customer_id">
<generator class="native" />
</id>
<property name="name" />
<property name="email" />
<property name="contact_person" />
<property name="postal_address" />
<property name="physical_address" />
<property name="contact_number" />
</class>
</hibernate-mapping>
HERE,
 “<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="CustomerRecords" namespace="CustomerRecords">…</ hibernate-
mapping>” is the root element of the mapping file. The element has xmlns, assembly
and namespace attributes. The assembly and namespace attributes should match your
project assembly and namespace values.
 “<class name="Customers">…</class>” defines the class element.
 “<id name="customer_id">…</id>” defines primary key. In our case its customer_id
 “<property name="field_name" />” matches the fields in the table that you wish to
manipulate using NHibernate.
For NHibernate to recognize our *.hbm.xml file, we need to set it as an embedded
resource. 
Click on Customers.hbm.xml file in Solution Explorer Set the Build Action to Embedded
Resource
NHibernate Connect to SQL Server
In this example, we will use an SQL Server database. Our database will have a single table. Run
the following script to create the database
CREATE DATABASE [CustomerRecordsDB]
GO

USE [CustomerRecordsDB]
GO

/****** Object: Table [dbo].[Customers] Script Date: 05/06/2015


14:51:02 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Customers](


[customer_id] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[name] [nvarchar](75) NULL,
[email] [nvarchar](95) NULL,
[contact_person] [nvarchar](75) NULL,
[postal_address] [nvarchar](150) NULL,
[physical_address] [nvarchar](150) NULL,
[contact_number] [nvarchar](50) NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[customer_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY =
OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

INSERT INTO [dbo].[Customers]


([name]
,[email]
,[contact_person]
,[postal_address]
,[physical_address]
,[contact_number])
VALUES
('Kode Blog'
,'a-team@kode-blog.com'
,'Rodrick Kazembe'
,'Private Bag WWW'
,'Tanzania'
,'911'),
('Google Inc'
,'info@google.com'
,''
,''
,'USA'
,'')
GO
Now that we have created our database. Let’s write the code that will connect to the database
Write the following code immediately after the FORM class definition. We want the defined
variable to be accessible by all the methods in our class

NHibernate Connection String


Configuration cfg = new Configuration();
Double click on the form Enter the following code in the form load event
cfg.DataBaseIntegration(x =>
{
x.ConnectionString = "Server=.; Database=CustomerRecordsDB;
Integrated Security=SSPI;";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2012Dialect>();
});

cfg.AddAssembly(Assembly.GetExecutingAssembly());

loadCustomers();
HERE,
 “cfg.DataBaseIntegration(x =>….);” sets the database connection string, database
driver and dialect.
 “x.ConnectionString “our connection string will connect to the local machine because
we set the server property to a dot. The database used is CustomerRecordsDB and we
are using integrated security.
 “x.Driver<SqlClientDriver>();” we will work with SqlClientDriver
 “x.Dialect<MsSql2012Dialect>();” we will use the dialect for SQL Server 2012. This will
make available the features in SQL Server 2012.

NHibernate Query using CreateCriteria. DataGrid


Example
We will use CreateCriteria to retrieve records from the database. Create criteria will produce a
simple query that will return all the records from the database. Alternatively, you can also add
restrictions to the returned results. Create a method called loadCustomers Add the following
code
private void loadCustomers()
{
var sessionFactory = cfg.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
var customers = session.CreateCriteria<Customers>()
.List<Customers>();

dgvCustomers.DataSource = customers;

tx.Commit();
}
}
}
HERE,
 “var sessionFactory = cfg.BuildSessionFactory();” creates a sessionFactory variable
from our configuration object
 “using (var tx = session.BeginTransaction())” creates a transaction from the session
variable”
 “var customers = session.CreateCriteria<Customers>().List<Customers>();” retrieves all
the record in Customers table and assigns the results to a list.
 “dgvCustomers.DataSource = customers;” assignes the list as the data source to the
data grid.

Executing Hibernate Query Language (HQL) in


NHibernate
Hibernate Query Langauge (HQL) is very similar to SQL. The following query retrieves a
customer record with a customer id 1.
"FROM Customers WHERE customer_id = 1"
HERE,
 “FROM…” indicates this is a SELECT query in SQL language
 “WHERE…” works the same as in SQL
Create a new method loadCustomer. This will only retrieve a single record and display the results
in text boxes for editing purposes.
private void loadCustomer(int customer_id)
{
var sessionFactory = cfg.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customers
WHERE customer_id = '" + customer_id + "'");

Customers customer = query.List<Customers>()[0];

txtCustomerID.Text =
customer.customer_id.ToString();
txtName.Text = customer.name;
txtEmail.Text = customer.email;
txtContactPerson.Text = customer.contact_person;
txtPhysicalAddress.Text =
customer.physical_address;
txtPostalAddress.Text = customer.postal_address;
txtContactNo.Text = customer.contact_number;

tx.Commit();
}
}
}
 
Complete NHibernate example source code
This section also adds the code for the command buttons. The code for the buttons is self-
explanatory. If you do not understand or need some clarifications then use the comments section
to ask.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NHibernate.Cfg;
using NHibernate.Driver;
using NHibernate.Dialect;
using System.Reflection;
using NHibernate;

namespace CustomerRecords
{
public partial class frmCustomers : Form
{
Configuration cfg = new Configuration();

private void loadCustomers()


{
var sessionFactory = cfg.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
var customers = session.CreateCriteria<Customers>()
.List<Customers>();

dgvCustomers.DataSource = customers;

tx.Commit();
}
}
}

private void loadCustomer(int customer_id)


{
var sessionFactory = cfg.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customers
WHERE customer_id = '" + customer_id + "'");

Customers customer = query.List<Customers>()[0];

txtCustomerID.Text =
customer.customer_id.ToString();
txtName.Text = customer.name;
txtEmail.Text = customer.email;
txtContactPerson.Text = customer.contact_person;
txtPhysicalAddress.Text =
customer.physical_address;
txtPostalAddress.Text = customer.postal_address;
txtContactNo.Text = customer.contact_number;

tx.Commit();
}
}
}

public frmCustomers()
{
InitializeComponent();
}

private void frmCustomers_Load(object sender, EventArgs e)


{
cfg.DataBaseIntegration(x =>
{
x.ConnectionString = "Server=.;
Database=CustomerRecordsDB; Integrated Security=SSPI;";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2012Dialect>();
});

cfg.AddAssembly(Assembly.GetExecutingAssembly());

loadCustomers();
}

private void dgvCustomers_Click(object sender, EventArgs e)


{
int customer_id = 0;

customer_id =
int.Parse(dgvCustomers.CurrentRow.Cells[0].Value.ToString());
loadCustomer(customer_id);
}

private void btnClear_Click(object sender, EventArgs e)


{
txtCustomerID.Text = "";
txtName.Text = "";
txtEmail.Text = "";
txtContactPerson.Text = "";
txtPhysicalAddress.Text = "";
txtPostalAddress.Text = "";
txtContactNo.Text = "";

txtName.Focus();
}

private void btnUpdate_Click(object sender, EventArgs e)


{
if (txtCustomerID.Text == "")
{
MessageBox.Show("Please select a record before you
update","No record
seleted",MessageBoxButtons.OK,MessageBoxIcon.Warning);

return;
}

var sessionFactory = cfg.BuildSessionFactory();


using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customers
WHERE customer_id = '" + txtCustomerID.Text + "'");

Customers customer = query.List<Customers>()[0];

customer.customer_id =
int.Parse( txtCustomerID.Text);
customer.name = txtName.Text;
txtEmail.Text = customer.email;
customer.contact_person = txtContactPerson.Text;
customer.physical_address =
txtPhysicalAddress.Text;
customer.postal_address = txtPostalAddress.Text;
customer.contact_number = txtContactNo.Text;

try
{
session.Update(customer);

tx.Commit();

loadCustomers();
}
catch(Exception ex)
{
tx.Rollback();
MessageBox.Show(ex.Message, "Exception
Msg",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}

private void btnAddNew_Click(object sender, EventArgs e)


{
if (txtName.Text == "")
{
MessageBox.Show("Please enter the name field", "No name
entered", MessageBoxButtons.OK, MessageBoxIcon.Warning);

return;
}

var sessionFactory = cfg.BuildSessionFactory();


using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customers
WHERE customer_id = '" + txtCustomerID.Text + "'");

Customers customer = new Customers();

customer.name = txtName.Text;
txtEmail.Text = customer.email;
customer.contact_person = txtContactPerson.Text;
customer.physical_address =
txtPhysicalAddress.Text;
customer.postal_address = txtPostalAddress.Text;
customer.contact_number = txtContactNo.Text;

try
{
session.Save(customer);

tx.Commit();

loadCustomers();
}
catch (Exception ex)
{
tx.Rollback();

MessageBox.Show(ex.Message, "Exception Msg",


MessageBoxButtons.OK, MessageBoxIcon.Error);
}

loadCustomers();
}
}
}

private void btnDelete_Click(object sender, EventArgs e)


{
if (txtCustomerID.Text == "")
{
MessageBox.Show("Please select a record before you
update", "No record seleted", MessageBoxButtons.OK,
MessageBoxIcon.Warning);

return;
}

var sessionFactory = cfg.BuildSessionFactory();


using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
IQuery query = session.CreateQuery("FROM Customers
WHERE customer_id = '" + txtCustomerID.Text + "'");

Customers customer = query.List<Customers>()[0];

try
{
session.Delete(customer);

tx.Commit();

loadCustomers();
}
catch (Exception ex)
{
tx.Rollback();

MessageBox.Show(ex.Message, "Exception Msg",


MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}
Summary NHibernate is a power simple to use ORM framework that can greatly enhance your
productivity.
What’s next?
If you hate XML files but love NHibernate then you might be interested in the tutorial Fluent
NHibernate Tutorial. Fluent NHibernate is NHibernate without the XML files.

You might also like