NHibernate Basics
Introduction
NHibernate is an Object-Relational Mapping (ORM) solution for the .NET Platform. It provides a framework for mapping an object oriented domain model to a traditional relational database. It's primary feature is mapping from .NET classes to database tables and from CLR data types to SQL data types.
As title of this article, we are going to see this feature only; How it loads business object from a database and saves changes from these objects back to the database.
Background
The demo application demonstrates in simple possible way how to setup and use NHibernate. The application creates an Employee object and stores it in a Employee table. It also does some operations like retrieval and deletion of Employee objects etc. The application is created with NHibernate 3.2.0, VS 2010 and SQL Server 2008.
Using the code
Database
Here we are going to setup the Database first. Use SQL Server Management Studio to create a database that can be used to elaborate with. As shown below create a new Database named NHibernateBasics.
Then add a table called Employee with two columns; ID and Name.
ID shall be the primary key and used as identity. Don’t forget to enable Identity Specification in the properties.
Business Object
The Database is ready for the demonstration. Now start Visual Studio and create a new WindowsFormsApplication project called NHibernateBasics. Add a new class called Employee.cs with the following code:
namespace NHibernateBasics
{
public class Employee
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
}
}
One of NHibernate's strongest features is that it doesn't need special interfaces on business classes. These objects are not aware of the mechanism used to load and save them. However it requires the properties declared as virtual so that it can create proxies as needed.
Mapping XML File
In the absence of specific code for hibernation, someone should guide the translation from the database to business object and back again. This can be achieved through either mapping xml file or by applying attributes on classes and properties. In the demo application we have used mapping file to keep our business object class clean.
Add a new XML file to the project. The XML file will be used as the mapping file. The name of the file must be Employee.hbm.xml. Both class <name>.cs file and mapping <name>.hbm.xml file should be in same folder and <name> should be same. Add the following content to the file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernateBasics" assembly="NHibernateBasics">
<class name="Employee" table="Employee">
<id name="ID" column="ID">
<generator class="identity"/>
</id>
<property name="Name" column="Name" />
</class>
</hibernate-mapping>
Configuration
Add a new application configuration file (app.config). Copy the following content:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="query.substitutions">hqlFunction=SQLFUNC</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=(Local)\SQL2008;Initial Catalog=NHibernateBasics;Integrated Security=True</property>
<property name="show_sql">true</property>
<mapping assembly="NHibernateBasics" />
</session-factory>
</hibernate-configuration>
</configuration>
Adjust the connection.connection_string property so that it works for your database. Set Catalog=<Database Name>; here it is NHibernateBasics. Set mapping assembly=<Class DLL Name>; here it is again NHibernateBasics.
Demonstration
Now we are almost ready for the demonstration. We just need to access the business class objects and perform certain operations on it.
Save
using(mySession.BeginTransaction())
{
mySession.Save(myInitialObjects[0]);
mySession.Save(myInitialObjects[1]);
mySession.Transaction.Commit();
}
Load
using(mySession.BeginTransaction())
{
ICriteria criteria = mySession.CreateCriteria<employee />();
IList<employee /> list = criteria.List<employee />();
for (int i = 0; i < myFinalObjects.Length; i++)
{
myFinalObjects[i] = list[i];
MessageBox.Show("ID: " + myFinalObjects[i].ID + " Name: " + myFinalObjects[i].Name);
}
mySession.Transaction.Commit();
}
Compare
StringBuilder messageString = new StringBuilder();
for (int i = 0; i < 2; i++)
{
messageString.AppendLine("Comparing Class Object " + myInitialObjects[i].Name + " and DB Object " + myFinalObjects[i].Name + ". Result = " + myInitialObjects[i].Equals(myFinalObjects[i]).ToString());
}
MessageBox.Show(messageString.ToString());
Delete
using (mySession.BeginTransaction())
{
mySession.Delete(myInitialObjects[0]);
mySession.Transaction.Commit();
}
Display
using (mySession.BeginTransaction())
{
ICriteria criteria = mySession.CreateCriteria<employee />();
IList<employee /> list = criteria.List<employee />();
StringBuilder messageString = new StringBuilder();
foreach (Employee employee in list)
{
messageString.AppendLine("ID: " + employee.ID + " Name: " + employee.Name);
}
MessageBox.Show(messageString.ToString());
}
NHibernate guarantees that two object references will point to the same object only if the references are set in the same session. If we save the objects in one session and load them in different session, then both the objects will be different objects. Hope it will help you to understand the basics of NHibernate. Happy coding :)
Points of Interest
Although there are many articles available for NHibernate, target audiance for this article are who just started learning NHibernate, including me :). Another nice article with more information is available here.History
发表评论
bFWHWQ Im obliged for the article post.Much thanks again. Will read on...
of healthier are estrogen made. As Is fibroids to pain of. Though your vagina process also as.