nHibernate ( Part 3)

Introduction:
In the last article we saw that how we can insert the data into the database using only few lines and without stored procedures. In this article we will look at some of the other cool features of NHibernate.
Retrieving a single record from the database:
You can easily retrieve a single record for a particular person based on the primary key. Just send in the primary key and you will be returned the object of the record.
private void Button1_Click(object sender, System.EventArgs e) { Configuration cfg = new Configuration(); cfg.AddAssembly("WebApplication1"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); Person person = (Person) session.Load(typeof(Person),1); Response.Write(person.Name); }
|
I have made the important line in bold. We are using session.Load method and sending the object type and the id of the object to pick up. In our database the id '1' belongs to 'Azam' and hence the object returned will contain information about Azam.
It is important to note that we are sending the 'PersonID' to the session.Load method and hence retrieving the live object. PersonID is also primary key in our database and an identity column. Since its an identity column we do not provide the set accessor in the PersonID property. But session.Load method requires that PersonID must have a set accessor in order to retrieve the record. In real application scenario you should have some other primary key like email or username so that you don't have to assign the identity column. |
Retrieving collection of objects:
You can also easily retrieve collection of objects. In the code below we are retrieving all the data from the table 'Person' and binding it to the datagrid.
private void Button2_Click(object sender, System.EventArgs e) { Configuration cfg = new Configuration(); cfg.AddAssembly("WebApplication1"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); IList personList = session.CreateCriteria(typeof(Person)).List(); DataGrid1.DataSource = personList; DataGrid1.DataBind(); } |
Retrieving objects based on Expression:
We can also retrieve objects based on Expressions. If we want to retrieve record of a Person whose name is 'Azam' we will just write something like:
IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.Eq("Name","Azam")).List(); |
In the above line we are simply adding an Expression just like the where clause in T-SQL. 'Eq' means Equal hence we are retrieving all the records where the property 'Name' is 'Azam'. It will return us with one record since there is only one record in the database with the name Azam.
You can also change the order of the rows retrieved. The order can be Ascending or Descending. In the code below I am retrieving the whole list and ordering them on the basis of the "Name" property in ascending order:
IList personList = session.CreateCriteria(typeof(Person)).AddOrder(NHibernate.Expression.Order.Asc("Name")).List(); |
If you have been working with T-SQL you should know that the 'IN' operator is one of the most important operators. Luckily we can use the 'IN' operator using NHibernate. The following code will return you the data of all the Person whose name is in the ArrayList. You can use any collection which implements the ICollection interface. I used Arraylist since it inherits the ICollection interface.
ArrayList myList = new ArrayList(); myList.Add("Azam"); myList.Add("Ali"); IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.In("Name",myList)).List(); |
You can also retrieve the results based on a certain range. Suppose you want all the people who work between two dates than you can use the following line.
IList personList = session.CreateCriteria(typeof(Person)).Add(NHibernate.Expression.Expression.Between("DateStarted", new DateTime(2005,01,01),new DateTime(2005,12,01))).List(); |
As you can see that now we are using the "Between" operator. There are lots of other operators that you can use depending on your need.
Please note that I have included two new properties "DateCreated" and "DateEnded" in Person.cs file which maps to the two new fields "StartDate" and "EndDate" in the database. |
Searching using NHibernate:
Searching is also very easy using NHibernate. Basically you just need to search in the collection and if the record with a particular search key is found you can take the appropriate action. In the code below we are searching for a Person name "Azam". If the person is found than a message is printed on the screen saying that "Person is found".
IList personList = session.CreateCriteria(typeof(Person)).List(); foreach(Person person in personList) { if(person.Name.Equals("Azam")) { Response.Write("Azam is in the list"); break; } else { Response.Write("Azam is not in the list"); } } |
You can also change the object properties and update it easily. Suppose that you want to change the date of the Person name "Azam" which is contained in the collection. Let's see how we can do this:
IList personList = session.CreateCriteria(typeof(Person)).List(); foreach(Person person in personList) { if(person.Name.Equals("Azam")) { person.DateStarted = DateTime.Now; person.DateEnded = DateTime.Now; session.Flush(); break; } else { Response.Write("Azam is not in the list"); } } |
As you can see above that we are simply finding the right person using the name property of the object. And than assigning the new Dates to the object and finally to make the changes we flush the session so that the changes appear in the database.
95% of all the operations that you can perform using T-SQL can be performed by using NHibernate classes.
Happy coding !

nHibernate (Part2)

Introduction:
I know you all must be really anxious to find out that how NHibernate works and how it can make your life easier. In this article we will look at the add feature of the NHibernate. I will go step by step so you understand what is going on.
Making a Class Library:
The first task is to create a class library which will be mapped using the NHibernate. So, lets make a simple class User.
public class User { private int personID; private string email; private string password; private bool status; private DateTime dateCreated;
// Defining properties public int PersonID { get { return personID; } set { personID = value; } } public string Email { get { return email; } set { email = value; } } public string Password { get { return password; } set { password = value; } }
public bool Status { get { return status; } set { status = value; } } public DateTime DateCreated { get { return dateCreated; } set { dateCreated = value; } }
|
As you can see that there is nothing special about the class. It has some private variables which you can access using the properties. All of this has been explained in my articles before.
NOTE:
All these properties will map to the database fields. That's why I have created the database script file for you. Just run the script file using query analyzer and it will create table for you. If it does not work than you can easily create a table based on the properties above. |
Creating Mapping File:
Now let's take a look at the mapping file for the User.cs class. This mapping file is called (User.hbm.xml). It's a good idea to name the mapping file based on the class name.
xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0"> <class name="Glasses.Test.User, Glasses" table="Person"> <id name="PersonID" column="PersonID" type="Int32" length="4" unsaved-value="0"> <generator class="identity" /> id> <property name="Email" column= "Email" type="String" length="50"/> <property name="Password" type="String" length="50"/> <property name="Status" type="Boolean" length="1"/> <property name="DateCreated" type="DateTime"/> class> hibernate-mapping> |
Let's take a look at the mapping file now.
- Glasses.Test.User is the name of the class that I am using. Glasses is the name of the assembly, Test is the name of the folder and finally user is the class.
- Person is the name of the table
- identity means that PersonID is the identity (Automatically generated) column in the database and we don't have to supply it.
- The
tags contain name which is the name of the property in the User.cs class. - column is the "database" column.
Note:
Make sure that the mapping file is configured as the "Embedded Resource". Right click on the "User.hbm.xml" file and select properties and set build option to "Embedded Resource". |
Add Method Code:
Now let's see the Add method that adds the user object into the database. In future articles we will implement an interface and inherit from that interface to get the common functionality. But for now let's look at the easy way to add the object.
public static void Add(User user) {// make the configuration file Configuration cfg = new Configuration(); cfg.AddAssembly("Glasses"); ISessionFactory factory = cfg.BuildSessionFactory(); ISession session = factory.OpenSession(); ITransaction transaction = session.BeginTransaction(); session.Save(user); transaction.Commit(); session.Close();
} |
- First we are making a Configuration object cfg
- We load the assembly using the AddAssembly method
- ISessionFactory interface creates a session factory which can be used to create sessions.
- ISession interface is used to create independent session which is opened by using the factory.OpenSession() method
- Once the session has been open than it means that you can communicate with the database.
- ITransaction interface which begines the session transactions.
- session.Save(user) is used to save the session.
- transaction.Commit() is used to save the data to the database.
- session.Close() finally closes the session.
The Client Code:
The Client code is pretty simple and self explanatory.
private void Button1_Click(object sender, System.EventArgs e) { User user = new User(); user.Email = "codersource@source.net"; user.Password = "mypassword"; user.Status = true; user.DateCreated = DateTime.Now; Test.User.Add(user);
} |
Don't wait now and check your database. A new entry should be added if you have done everything right. Isn't this the coolest thing ever. In the upcoming articles we will see more features of NHibernate.
I hope you enjoyed the article. Happy programming !

Introduction to Object Relational Mapping with nHibernate (Part1)

Introduction:
We all are familiar with datasets which is a carrier used to carry data from one layer to another. In my previous article I described some of the pitfalls of using datasets. Datasets are most commonly used when we are accessing database. The common pattern of accessing data from the database is given in the following steps:
1) Make connection to the database
2) Make DataAdapter
3) Execute commands using dataadapter or command objects using stored procedures or Ad-hoc queries.
4) Fill the dataset using dataadapter
5) Bind dataset to the control on the webform.
The above procedure does not look that long but consider doing this over and over and over again. What will happen when some database field you misspelled and now its occurring in 200 stored procedures. You need to tell your Boss that you need a week or even more to fix this simple spelling problem. Not only that but migration can also be a big problem. If you have a stored procedure that takes 5 seconds to execute (Although 5 seconds is too long) and some one tweaked the procedure so now it runs in <>
What if I told you that you can insert, delete, update, edit in other words perform all type of database operations without executing any SQL at all. This seems impossible and kind of a crazy thought but this is what O/R Mapping is all about. O/R Mapping also known as Object Relationship Mapping which allows us to map our data in file(s) and use those mapping files to retrieve or add data to the database. The main idea behind the O/R Mappings is relationships. Consider the following query:
SELECT Person.Name, Person.Email FROM Person,Customer WHERE Person.PersonID = Customer.CustomerID |
As you can see that Person table and the Customer table has relationship between them which let's them perform different actions. Just in the same way O/R mapping is also relationships and these relationships can be created in files.
There are many O/R Mappers available to download. Some are free and some are pretty expensive. In this article and for the rest of the series we will be looking at the NHibernate O/R Mapper which is a free and open source. You can download the NHibernate O/R Mapper from http://nhibernate.sourceforge.net/ .
Here is a list of different O/R Mappers (List of O/R Mappers)
When not to use O/R Mapping:
You should not use O/R Mapping when your business logic is dependent on complex stored procedures. Having said so if you have business logic implemented in stored procedures than you have another thing coming :). Almost 95% of all the stored procedures that you write can be represented by O/R Mapping.
Installing NHibernate:
Installation is pretty simple. I assume you downloaded the Zip file from http://sourceforge.net/project/showfiles.php?group_id=73818. Once you done downloading simply extract it on your hard drive. It will have different folders inside the main directory, some of those folders contains the code and some have different type of files. Your concern will be the .dll files in the bin directory.
