NHibernate is an open source Object-Relational Mapping (ORM) tool for the .Net platform. Here each row in the database acts as an object. If we write a sql query to get data from database, it gives list of rows. In nhibernate, we get list of objects insted of rows. Working with nhibernate is very simple. All We need to know is just how to configure the settings. Here i am trying to explain this tutorial from the scratch. Follow the below steps carefully.
Step1: The following are some Requirements to work with Nhibernate
1.Microsoft Visual Studio 2008 or greater
2. SQL Server Management Studio
Note: I am assuming that you already have the above two installations.
Step2: We need Nhibernate library files. You can download these files from following source.
Step3: After downloading Nhibernate library, go to Required_Bins folder
Path: NHibernate-3.3.1.GA-bin-->Required_Bins
After opening Required_Bins you will see nhibernate-configuration.xml, nhibernate-mapping.xml files. Copy these two files and paste it into C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas folder.
Step4: Now we need to connect the database. Do the following steps.
Step 4.1: Open the visual studio and right click on view and select server explorer.
Step 4.2: After choosing server explorer you will see the following window. Then right click on Data Connections and select add connection.
Step 4.3: After choosing add connection, you will see the following window. Then select the Microsoft SQL Server and uncheck the "Always use this selection" check box and finally click on continue button.
Step 4.4: After choosing continue button you will see the following window.
Step 4.5: Here you have to fill server name. To get the server name, see next tab below the Data Coonections. Inside Servers root , list of servers will be there.In your system the name may be different.I am showing server name in my system. See the following window.
Step 4.5: Enter your server name.
Note: You should use your server name.
Step 4.6: Select "Use SQL Server Authentication" radio button and fill your username and password. and click ok.
Step 4.7: After choosing ok you will see the following database.
Step 4.8: So expand the database and right click on tables and select "Add New Table". Then a window will be opened to enter the table fields. In this tutorial i want to use employee table. So fill the details as follows.
Step 4.9: select the first row and set the primary key by clicking on the key symbol.
step 4.10: Again select the empId column in table, and below the table you will see column properties, In that Expand the Identity Specification tab, and change isIdentity to yes.
step 4.11: After changing, Save the table name with Employees.
Now our database part is done!!.
Step 5: Come to the visual studio. Create a new Project.Then select console application and type the project name as NhibernateTutorial.
Step 7: Create variables and methods exactly same as below. Here each variable represents a column in the Employee table. So it is better to create field names exactly same as database including capital and small letters. Here you must use virtual keyword. Otherwise it will give error.
Step 8: After creating entity class,we need to write hibernate mapping file. This is an xml file. To create this, right click on the project and click on Add and select new Item.
Step 9: After choosing new Item,you will see the following window. So select on data which is available at right side and select XML file, and write file name as Employee.hbm.xml as below.
Step 10: Write the configuration detais as follows.
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NhibernateTutorial" namespace="NhibernateTutorial">
<class name="NhibernateTutorial.Employee,NhibernateTutorial" table="Employees">
<id name="empId" column="empId" type="Int32" unsaved-value="0">
<generator class="native">
</generator>
</id>
<property name="empName" column="empName" type="String" not-null="true"></property>
<property name="city" column="city" type="String" not-null="true"></property>
</class>
</hibernate-mapping>
Note: You should use your assembly name and namespace name in the above mapping xml.
Explanation:
Hibernate-mapping tag: It is the root tag for nhibernate mapping xml. It contains three attributes. They are
xmlns: It represents xml namespace. So after writing "xmlns=" in xml file, if we press (ctrl+space bar) it will show list of options from that we can select the urn:nhibernate-mapping-2.2 value.
assembly: It represents the assebly name of your project. You can get this name by right clicking on the project and select properties. You will see the following window.
namespace: It represents the namespace of your project.
Class tag: It represents an entity class, which is the equivalent representation of the table in database. It will take the follwoing attributes.
name: Name attribute takes two parameters. First one is class name and the second one is assembly name.
table: It represents the table name in the database.
Id tag: It represents the primary key in the table.
name: It represents field name in the entity class which is equivalent to the column name in the table.
column: It represents column name in the corresponding table.
type: It represents data type of the field name in entity class which is equivalent to the data type of corresponding column in the database table.
unsaved-value: unsaved-value is used to differentiate whether we are going to insert the data or update the data. Here we are setting it to zero. So if the value is zero then nhibernate assumes that it is a new record. So that it will insert the data. If it is a non zero, then nhibernate assumes that it is an existing record. So it will perform update operation.
generator tag: It represents whether we have to fill the field value or database fills.
class: It represents who will take care of filling the primary key field value. Here the "native" represents database will take care of filling the primary key field.
property tag: It represents the field name in entity class which is equivalent to colum name in the database table.
Step 11: After writing the mapping details, right click on the Employee.hbm.xml file and click on the properties and change the Build Action to embedded resource.
Step 12: Now we will create a class to get employee data using nhibernate from database. Before creating that class, we need to add some nhibernate library files. It can be done as follows.
Step 12.1: Right click on the References and select Add Reference.
Step 12.2: Then you will see the following window. From this you can select Required_Bins folder from NHibernate-3.3.1.GA-bin, which you downloaded from our website. The Required_Bins folder contains NHibernate.dll. So select that NHibernate.dll and click ok.
Step 13: Now right click on the project and create a new class and name the class as NhibernateDataProvider. Write the follwoing content in the NhibernateDataProvider class.
NhibernateDataProvider.cs Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace NhibernateTutorial
{
class NhibernateDataProvider
{
public Employee getEmployeeById(int employeeId)
{
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
return session.Get<Employee>(employeeId);
}
}
}
Step 14: Finally we call the methods in the main method. So go to program.cs and write the following code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NhibernateTutorial
{
class Program
{
static void Main(string[] args)
{
NhibernateDataProvider obj = new NhibernateDataProvider();
Console.WriteLine(obj.getEmployeeById(2).empName);
}
}
}
Note: ( Please fill some data in employee table before executing the program).
Step 15: Now the last step is to set up configuration file. This is an xml file. so right click on the project, and select new Item and then click on data and select the xml file. Save the file as hibernate.cfg.xml.
Step 16: Write the following code in it.
hibernate.cfg.xml :
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=SL-PN-LT-0064;User ID=sa;Password=mysql@123</property>
<property name="show_sql">false</property>
<mapping assembly="NhibernateTutorial"/>
</session-factory>
</hibernate-configuration>
Note:
1.Here when writing xmlns, if you press (ctrl+space bar) it will give list of options. From that you can select, the value "urn:nhibernate-configuration-2.2"
2. When writing coonection string, you should use your connection string. This connection string you can get by right cliking on the database connection in the visual studion and select properties. From properties window you can copy the connection string and paste in the xml file.
3. Use you assembley name when writing assembly.
Step 17: Right click on the hibernate.cfg.xml and select properties. Then change the Copy to output directory option to "copy always".
Step 18: Finally Run the program.cs file.
Note: ( Please fill some data in employee table before executing the program).
Here i explained how to work with nhibernate by giving simple example. So if you get this, you can improve your knowledge by reading relationships and mappings in nhibernate.
http://horoscope.vikianswers.com/
http://horoscope.vikianswers.com/
This is the most clean explanation I have seen so far. thanks for your effort!
ReplyDeleteNice Explanation along with Pictures , Great Effort, Thanks a LOT.
ReplyDeleteGreat Work,Thanks a lot
ReplyDeletenice....thanks really helpful
ReplyDeleteGreat Work man!!
ReplyDeleteGooooooooood!!!!!!!!!!
ReplyDeleteVery nice example ....i like
ReplyDeleteHow to insert value using Nhibernate ..plz tell
ReplyDeleteHoroscope
ReplyDelete