Geeks With Blogs
Guilherme Cardoso, Blog EN .NET geek

Note: I've translated this article from my Portugues blog: http://pontonetpt.com/blogs/guilhermecardoso/archive/2010/06/12/nhibernate-introdu-231-227-o.aspx
I'm sorry for the bad english, but i'll try to translatet it better as possible with a little help of Google Translatter.
I've writed this article because i coulnd't found one article about NHibernate 2.0 that was simple to understand in Portuguese.


 

In the coming weeks I will spend some free time studying NHibernate.


I've heard very good reviews about this ORM but when I started trying to study it and learn how to use it I began to think it was quite tricky! Now I begin to understand the architecture begin to notice that it is not that complicated, my problem was to find material to study (in Portuguese). To be honest I'm locked in the room since yesterday late afternoon, just to be able to understand what I'm writing this article ..

So I decided to start writing articles on a journey of initiation of NHibernate! As you are learning new features I'll post on my blog (i'll post here too).

If anyone happen to notice errors please let me know, I have yet to start me on this ORM and want to earn good grounding in it.

The source code of this article is available for download: http://github.com/guilherme-cardoso/NHibernate---Introdu--o/downloads

 

 


NHibernate

The NHibernate is an ORM based on another ORM for Java, Hibernate. His job is to map the class of our project with the database without having to worry about SQL commands.

Farther down the part of the methods, we notice three interfaces used (except IQuery that will be later on):

  • ISession  - represents a connection to the database
  • ITransaction - represents a transaction controlled by NHibernate
  • IQuery - represents a query to the database


These three interfaces belong to the assembly NHibernate.dll

 


Installation

Unlike the Entity Framework which is already built into Visual Studio, NHibernate requires a manual installation.
It's very simple, just download  NHibernate (here). When creating a new project, we add the following references:

  • NHibernate.dll (NHibernate-2.1.2.GA-bin\Fluent NHibernate)
  • NHibernate.ByteCode.Castle.dll (NHibernate-2.1.2.GA-bin\Fluent NHibernate)
  • Castle.Core.dll (NHibernate-2.1.2.GA-bin\Fluent NHibernate)

For later create projects without having to download the NHibernate again, i've extract the download to a folder in C: / and when I create new project, add references starting from there.

Using a proxy is required by NHibernate. In this example I'm using the Castle but I will not talk about it in this article because I do not know what it is! Later there will.

 


Configuration

To configure NHibernate i've seen in quite a few tutorials developers creating the hibernate.cfg.xml file and when it is calling the method Configure () of the assembly NHibernate.Cfg.Configuration, NHibernate will look for this file and apply the settings.

I preferred to create inside the Web.Config.
Next to tag  <ConfigSections> (percent to <configuration>) we add a new section and then we add the configuration of NHibernate with the name of this section (hibernate-configuration):

<configuration>
	<configSections>
		<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
	</configSections>

Next to tag </configSections> i've inserted the NHibernate configuration.

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
        <session-factory>
            <property name="dialect">
                NHibernate.Dialect.MsSql2005Dialect
            </property>
            <property name="connection.provider">
                NHibernate.Connection.DriverConnectionProvider
            </property>
            <property name="connection.driver_class">
                NHibernate.Driver.SqlClientDriver
            </property>
            <property name="connection.connection_string">
                Server=Computador\SQLEXPRESS;
                Database=NHibernate;
                Integrated Security=True;
            </property>
            <property name="proxyfactory.factory_class">
                NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle
            </property>
        </session-factory>
    </hibernate-configuration>

You'll need to change the name of your SQL server on the property connection.connection_string. The name appears when starting the SQL Server 2005 (in the dialog box to connect to the server).

I am using a SQL Server 2005. If they are not working with these databases, you can see an article that Leandro Ribeiro wrote on database supported by NHibernate:
http://pontonetpt.com/blogs/leandroribeiro/archive/2008/02/22/P26588.aspx

 


Mappings

Configured NHibernate let's create the mappings.
Form now, we
will do the mappings using. XML (traditional NHibernate), but later on I will use the Fluent NHibernate. The Fluent NHibernate allows us to make our mappings in code (instead of XML files) and also has the characteristic of creating mappings automatic starting of our bodies (not sure if some tool for NHibernate create something like that in XML).

To better structure our project, we will create a folder named Mappings. Inside that folder we'll create an XML file named News.hbm.xml.
One important aspect is the extension. Hbm.xml. The NHibernate will recognize all files that contain hbm before the extension .Xml mapping files.

Before we get to write our mapping we will use an xml schema that was in the beginning we did download for Visual Studio and Intellisense in facilitating the work while we are writing the code. The file is called NHibernate-mapping.xsd and is inside the folder Required_Bins. To change the schema we entered into the file News.hbm.xml, we put the cursor inside the area code as if we were to write something and in the properties window will show a field named Schemas. Here we indicate where the file is NHibernate-mapping.xsd

For now we will only create a table named News and three columns: Id, Title and Body.

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NH" namespace="NH.Dominio">
    <class name="News" table="News">
        <id name="Id" column="Id">
            <generator class="native" />
        </id>
        <property name="Title"></property>
        <property name="Body"></property>
    </class>
</hibernate-mapping>

The namespace is NH.Dominio indicate where we have the entity regarding this mapping (which we will create next ).
The Id column is represented with its own tag <id> and as in this example is auto-incrementing, defended the generator class as native.

 


Entitys

The entities are written in code. Are the objects of our mappings.
Inside the folder Dominio let's create a class file named News.cs.
Let's create a class (table) named News and declare three objects: Id, Title and Body

namespace NH.Dominio
{
    public class News
    {
        public virtual Int32 Id { get; set;}
        public virtual string Title { get; set; }
        public virtual string Body { get; set;}
    }
}

You must assign the variables to virtual property that NHibernate can work with them.

 


Context

This layer will be responsible for liaison between our program and NHibernate, which in turn connects to the database.

public class Contexto
    {
        private static ISessionFactory _sessionFactory;
        private static ISessionFactory SessionFactory
        {
            get
            {
                if(_sessionFactory == null)
                {
                    string directory = System.Web.HttpContext.Current.Server.MapPath(@"~/Dominio/");
                    NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
                    configuration.AddXmlFile(directory + "News.hbm.xml");
                    configuration.Configure();
                    _sessionFactory = configuration.BuildSessionFactory();

                }
                return _sessionFactory;
            }
        }
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }

It will just create a new session if it still has not been created (provided _sessionFactory == null).
It's also where we include our mapping settings of News. I created the directory string for showing the way when I added the XML file
.

 


CRUD (Create, Read, Update e Delete)

Now that we have configured NHibernate, create mappings and entities we can write the CRUD methods.

The CRUD methods we put in a layer from which we create, the layer Dal.cs. This will help us to maintain our program esturutra organized.

Insert

public void News_Create(News ne)
        {
            using (ISession session = Contexto.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Save(ne);
                transaction.Commit();
            }
        }

 

Delete

public void News_Delete(News ne)
        {
            using (ISession session = Contexto.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Delete(ne);
                transaction.Commit();
} }


Note: It is not necessary to close the session (Session.Close) because the block using that uses the Session variable will be automatically released from memory.

Uppdate

public void News_Update(News ne)
        {
            using (ISession session = Contexto.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Update(ne);
                transaction.Commit();           
            }
        }
 
Again, the only difference we noted is the Update.

Get By ID

public News News_GetByID(int id)
        {
            using (ISession session = Contexto.OpenSession())
            {
                return session.Get<News>(id);
            }
        }

Return an List

public List<News> News_ReturnList()
        {
            using (ISession session = Contexto.OpenSession())
            {
return session.CreateCriteria(typeof(Noticias)).List<News>(); } }

 

 

Some useful links:
NHibernate Portugal (mailling list atgoogle): http://groups.google.com/group/nhpt
NHusers (mailling list at google): http://groups.google.com/group/nhusers
NHibernate forum: https://forum.hibernate.org/viewforum.php?f=25

Posted on Friday, June 18, 2010 5:10 AM | Back to top


Comments on this post: NHIbernate 2.0 - Introduction

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Guilherme Cardoso | Powered by: GeeksWithBlogs.net