.NET NHibernate tutorial #2 – Sample configuration

This article is the second part of series of articles about .NET NHibernate usage.
In the series we work with tools that can be used in commercial projects freely:
1. Visual Studio 2012 Express for Desktop http://bit.ly/QLJsJT (note that this tool is dedicated to creating desktop applications. If we want to build web-based applications, we need to install Visual Studio 2012 Express for Web)
2. SQL Server 2012 Express http://bit.ly/KJIAMR
3. NHibernate 3.3.3. package http://nhforge.org/

To initiate the NHibernate configuration in Visual Studio 2012 Express we need to add two reference files to our project (in our example we use Console Application): lesi.Colletions.dll and NHibernate.dll (it is described in details in the article NHibernate – First Step).
Before we start the configuration itself, we also have to create a database and a sample table with some data.
To do that, we open Microsoft SQL Server Management Studio and connect to our SQL Server first. When it is done, we right-click the Databases section and select New Database…. In the Database name section we should type a name of our database, for example ItCutiesDemo, and confirm it with the OK button (Capture 01).

.NET NHibernate - Capture 01. Creating a new database

.NET NHibernate – Capture 01. Creating a new database

We have got our database ready now. To create a sample table we need to expand ItCutiesDemo and right-click Tables. Next, we select New Table... what results in opening the table in design mode.
Let us add three columns like shown in Table 01 below:

Table 01. Database schema.

Column Name Data Type Allow Nulls
CustomerId Int NO
FirstName nvarhcra(50) NO
LastName nvarchar(50) NO

Then, we right-click the CustomerId column and select Set Primary Key.

The last step is to have our ID added automatically. In the right side of the window, we find a row named Identity Column. We need to set CustomerId as its value and confirm that with Save or Ctrt+S combination. We give this table name Customer. Our table should look like the one below (Capture 02):

.NET NHibernate - Capture 02. Customer table in design mode

.NET NHibernate – Capture 02. Customer table in design mode

To add some sample data we right-click on our table dbo.Customer (if we don’t see it, we need to refresh our database by right-clicking the database named ItCutiesDemo and selecting ‘Refresh’), select Edit Top 200 Rows and add sample data to get the results like below (Capture 03):

.NET NHibernate - Capture 03. Sample data

.NET NHibernate – Capture 03. Sample data

Note: If we already have a database with some data (for example Database with samples data.sql added to this article), we skip the above steps. In that case we need to launch our Microsoft SQL Server Management Studio and open the database file there.

Now, we can go back to Visual Studio and our NHibernate configuration. We open Program.cs first, what should give the result similar to ‘Capture 04′. Our program does nothing, so let us write some code.

.NET NHibernate - Capture 04. Newly opened Program.cs

.NET NHibernate – Capture 04. Newly opened Program.cs

In the using section we can leave only using System; deleting other using entitles and then add some new ones to our code like below:

using System.Reflection;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;

The next step is configuring the connection to our database. In that purpose in the static void Main(string[] args) section we have to write the following code:

var configuartion = new Configuration();
configuartion.DataBaseIntegration(x => {
	x.ConnectionString = "Server=.//SqlExpress; Database=ItCutiesDemo; Integrated Security=SSPI;";
    x.Driver<SqlClientDriver>();
    x.Dialect<MsSql2012Dialect>();
});

The above code determines how NHibernate connects to the database. ConnectionString indicates the name of the server, then we specify the database name and, if we use windows logon for the database, we type Integrated Security=SSPI;.
Next, we choose a database driver. We can choose among many types of databases, like: SQL Server, Oracle, DB2, Firebird, Informix, Ingres, MySQL, PostgreSQL, SQLite, SQL Server CE, Sybase or any ODBC- or OleDb- compliant data source. As we use Microsoft SQL Server database in our example, this fragment of our code looks like that: x.Driver();
Finally we need to determine which database version we want to connect to (line: x.Dialect)There, we can choose between SQL Server 2000, SQL Server 2012 or SQL Server Azure. In this example, we connect to SQL Server Express 2012 typing: x.Dialect();

Now, when our project can connect to the database with NHibernate, we need to provide a model list by adding an assembly. We want to get the assembly when the code is being executed, so we type: configuartion.AddAssembly(Assembly.GetExecutingAssembly());
Then we need to write a method that tells NHibernate how to translate C# classes to MSSQL. In that purpose we create sessionFactory that will build the session and transaction of everything we want to do with our database in our C# code.

var sessionFactory = configuration.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
	using (var transaction = session.BeginTransaction())
    {
		// database logic
        transaction.Commit();
    }
}

The subsequent step is adding mapping to our project. Mapping itself will be prepared in an xml file; that is the reason why we need to add a new file to our project (right-click on the project, select New Item... and find XML File named Customer.hbm.xml). In the xml file, we need to configure NHibernate like below:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
				assembly="ItCuties.NHibernate"
               	namespace="ItCuties.NHibernate">
	<class name="Customer">
		<id name="CustomerId">
			<generator class="native" />
		</id>
		<property name="FirstName" />
		<property name="LastName" />
	</class>
</hibernate-mapping>

At first we tell our code that, for the mapping purpose, we use NHibernate for the ItCuties.NHibernete project. As the base class is Customer we type that information next. Another important information is Id – identifier for row in the database where our data is stored. Subsequent properties are other columns in our table and we need to add every column chosen in the database (nulls are not allowed).
Next, in Solution Explorer, we right-click the NHibernate.hbm.xml file and choose Properties. There we change the Build Action value from Compile to Embedded Resource (see ‘Capture 05′). In that way we have indicated which source is an embedded resource mapping file. This is necessary as we want to get the assembly when the code is being executed.

.NET NHibernate - Capture 05. Setting Embedded Resource

.NET NHibernate – Capture 05. Setting Embedded Resource

Now, we can create a new Customer.cs class that clones indicated rows from the table. We write a code like below:

namespace ItCuties.NHibernate
{
	public class Customer
	{
    	public virtual int CustomerId { get; set; }
    	public virtual string FirstName { get; set; }
    	public virtual string LastName { get; set; }
	}
}

Note that the class itself and its properties are public. They cannot be different as NHibernate cannot read from other levels of protection than public. All properties are virtual because NHibernate needs it for lazy loading.
Now we are ready to go back to Program.cs and replace a comment // database logic with a destination code:

var customers = session.CreateCriteria<Customer>().List<Customer>();
foreach (var customer in customers)
{
	Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
}

When we Run our program we will see the list of data items obtained from SQL Server (Capture 06).

.NET NHibernate - Capture 06. Result of program execution

.NET NHibernate – Capture 06. Result of program execution

To summarize, our code listing should look like below:

Customer.cs

namespace ItCuties.NHibernate
{
	public class Customer
	{
    	public virtual int CustomerId { get; set; }
    	public virtual string FirstName { get; set; }
    	public virtual string LastName { get; set; }
	}
}

Customer.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
               	assembly="ItCuties.NHibernate"
               	namespace="ItCuties.NHibernate">
	<class name="Customer">
		<id name="CustomerId">
			<generator class="native" />
		</id>
		<property name="FirstName" />
		<property name="LastName" />
	</class>
</hibernate-mapping>

Program.cs

using System;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
using System.Reflection;
 
namespace ItCuties.NHibernate
{
	class Program
	{
    	static void Main(string[] args)
    	{
        	var cfg = new Configuration();
        	cfg.DataBaseIntegration(x =>
        	{
            	x.ConnectionString = "Server=.\\SqlExpress; Database=ItCutiesDemo; Integrated Security=SSPI;";
            	x.Driver<SqlClientDriver>();
            	x.Dialect<MsSql2012Dialect>();
        	});
        	cfg.AddAssembly(Assembly.GetExecutingAssembly());
        	var sessionFactory = cfg.BuildSessionFactory();
        	using (var session = sessionFactory.OpenSession())
        	{
            	using (var tx = session.BeginTransaction())
            	{
                	var customers = session.CreateCriteria<Customer>()
                        .List<Customer>();
                	foreach (var customer in customers)
                    {
                        Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
                    }
                	tx.Commit();
            	}
            	Console.WriteLine("Press <ENTER> to exit...");
            	Console.ReadLine();
        	}
    	}
	}
}

Download this sample code here.

This code is available on our GitHub repository as well.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Java by Example App is available at Google Play Store NOW