戰地連結︰ Home My Flickr NBA.com About

2008年8月4日星期一

Hibernate for .NET - NHibernate Setup

Overview

Hibernate offers O/R mappings between Database and Java persistence classes. Many Java programmers get used to Hibernate would like to use the same technology (and syntax!) on their .NET projects too~ The answer to this is called NHibernate.
Below I will share my experience on how to set up NHibernate with C#, it should be similar for other .NET languages.

Reference

  1. NHibernate Tutorial (1) - and ASP.NET
  2. Installation And Running NHibernate
  3. Your first NHibernate based application

Environment

  • Database: SQL Server 2005
  • NHibernate: 1.2.1 GA
  • .NET Language: C#

Steps

Setup SQL Server Database

  1. It is assumed that your Database is setup properly, so I will skip this step.

Download and install NHibernate

  1. Download NHibernate at Here (I downloaded 1.2.1 GA-bin.zip)
  2. Extract the zip file and navigate to folder "net-2.0"
  3. We are going to use "NHibernate.dll" as reference in our project

Create Web Site and do NHibernate Configuration in VS

  1. Add a Web Site to your Solution, and a C# class library project with name "Solution.Domain".
  2. There are two ways to do configuration for NHibernate, one is by "System.Configuration.NameValueSectionHandler", the other is by "NHibernate.Cfg.ConfigurationSectionHandler". I choose to use method 2 because it is supported in NHibernate 2.0
  3. Open "web.config" file and add "hibernate-configuration" section with the following code snippet:

    <configuration>

      <configSections>

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

      </configSections>

      <!--

            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="hibernate.connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

          <property name="connection.connection_string">Server=(local);Initial Catalog=Test;Integrated Security=SSPI;</property>

          <mapping assembly="Solution.Domain" />

        </session-factory>

      </hibernate-configuration>

    </configuration>

  4. Now we have the "web.config" ready, we still have to add two helper classes for handling NHibernate sessions. I extracted This zip file attached to Reference 1 and used the "NHibernateHttpModule.cs" and "SessionHelper.cs" files.
    However, I modified "SessionFactory" method in "SessionHelper.cs" as my configuration method is different from that of Reference 1.

    My modified "SessionFactory" method:

    private static ISessionFactory SessionFactory

            {

                get

                {

                    if (_sessionFactory == null)

                    {

                        Configuration config = new Configuration();

                        config.Configure();

                        _sessionFactory = config.BuildSessionFactory();

                        if (_sessionFactory == null)

                            throw new InvalidOperationException("Could not build SessionFactory");

                    }

                    return _sessionFactory;

                }

            }

Defines Mapping and the persistence class

  1. The NHibernate mapping file is just like that of Hibernate: A XML file with extension ".hbm.xml". Here is my mapping file:

    <?xml version="1.0" encoding="utf-8" ?>

    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Solution.Domain" assembly="Solution.Domain">

     

      <class name="User" table="app_user">

        <id name="Username" column="username" type="String">

          <generator  class="assigned"/>

        </id>

        <property name="Name" column="name" type="String"/>

        <property name="Password" column="password" type="String"/>

      </class>

       

    </hibernate-mapping>

  2. This XML mapping file must be included in the assembly with the name "Solution.Domain". To do this, right-click on the XML mapping file and select "properties", then choose "Embedded Resource" for "Build Action".
  3. Next, let's move on to the persistence class.

    namespace Solution.Domain

    {

        public class User

        {

            public User()

            {

            }

     

            public virtual string Username

            {

                get;

                set;

            }

            public virtual string Name

            {

                get;

                set;

            }

            public virtual string Password

            {

                get;

                set;

            }

        }

    }

Show the result in ASP.NET page

  1. Add a aspx page to the Web Site and then add the following code snippet to the aspx page:

    protected void Page_Load(object sender, EventArgs e)

        {

            ISession session = NHibernateHttpModule.CurrentSession;

            IQuery query = session.CreateQuery("FROM User");

            IList result = query.List();

     

            GridView1.DataSource = result;

            GridView1.DataBind();

        }

  2. If everything works fine (and you have some Data in your SQL Server Table!), then you should see the data is retrieved and displayed on the aspx page~

1 則留言:

匿名 說...

您好:
剛好在網站上看到你寫的NHibernate,因剛好目前工作上需要demo NHibernate,碰到一些問題,想藉由你的程式來看看哪邊出錯。因此是否方便將你的source code寄給我。如果可以的話,請寄到ferry.chang@msa.hinet.net
謝謝

BR,
Ferry