I've been playing around with NHibernate for an afternoon and am very impressed. I started with the Quick Start Guide. NHibernate maps fields in C# objects into a database without the programmer having to directly specify the SQL code to do it. NHibernate also handles caching of objects. This frees the programmer to concentrate on the business logic and not getting objects into and out of a database. Free utilities can convert between c# classes, .hbm.xml, and database schemas.

You can download NHibernate at http://nhibernate.sourceforge.net. For this example, you will also need NUnit, since the NUnit tests do all the work.

  1. Example C# class

    To show a very easy example, I'll use the following class. Note that all the members going into the database have accessors.

    
    using System;
    using NUnit.Framework;
    using NHibernate;
    using NHibernate.Cfg;
    using System.Reflection;
    
    namespace SDLite {
    	/// <summary>
    	/// Tiny program to demonstrate NHibernate
    	/// </summary>
    	public class Survey {
    		private String name;
    		private String groupName;
    		private int status;
    		private int priority;
    
    		public Survey(){}
    		public Survey(string name, string groupName, int priority, int status) {
    			this.Name = name;
    			this.GroupName = groupName;
    			this.Priority = priority;
    			this.Status = status;
    		}
    		//NHibernate needs accessors
    		public string Name {get{return name;}set{name=value;}}
    		public string GroupName {get{return groupName;}set{groupName = value;}}
    		public int Status {get{return status;}set{status=value;}}
    		public int Priority {get{return priority;}set{priority=value;}}
    	
    		public override string ToString() {
    			return "Survey\r\n Name:"+Name+"\r\n GroupName: "+GroupName+"\r\n Status: "+Status+"\r\n Priority: "+Priority+"\r\n";
    		}
    	}
    ...
    
  2. Next, we need to create the table in the database:

    create database NHibernate
    use NHibernate
    go
    
    CREATE TABLE Surveys (
      Name nvarchar(40) default NULL,
      GroupName nvarchar(40) default NULL,
      Status int default 0,
      Priority int default 10,
    
      PRIMARY KEY  (Name)
    )
    go
    
    
  3. Mapping file

    The first thing needed is a mapping file to tell NHibernate how to map the fields in your object to the table and columns in a database. This needs to be an embedded object if you are using Visual Studio. In the "class" element, the second argument in the "name" attribute is the assembly name, so NHibernate can reflect the objects. Here's our Survey.hbm.xml file:

    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
    	<class name="SDLite.Survey, SDLite" table="Surveys">
    		<id name="Name" column="Name" type="String" length="40"> 
    	       <generator class="assigned" /> 
    	    </id> 
    		<property name="GroupName" column= "GroupName" type="String" length="40"/> 
    		<property name="Status" type="integer" /> 
    		<property name="Priority" type="integer"/>
    	</class>
    </hibernate-mapping>
    
    
  4. Database connection information

    In the app.config file we need to tell NHibernate how to connect to the database server.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section 
          name="nhibernate" 
          type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" 
        />
      </configSections>
    	
      <nhibernate>
        <add 
          key="hibernate.connection.provider"          
          value="NHibernate.Connection.DriverConnectionProvider" 
        />
        <add 
          key="hibernate.dialect"                      
          value="NHibernate.Dialect.MsSql2000Dialect" 
        />
        <add 
          key="hibernate.connection.driver_class"          
          value="NHibernate.Driver.SqlClientDriver" 
        />
        <add 
          key="hibernate.connection.connection_string" 
          value="Trusted_Connection=yes; Data Source=Marvin; Trusted_Connection=yes; database=NHibernate" 
        />
      </nhibernate>
    </configuration>
    
    
    
  5. Using NHibernate in NUnit tests

    This TestFixture is embedded in the .cs file. We can create, edit, and delete Survey objects without ever having to write a line of SQL. Best of all, if the database schema changes, only the .hbm.xml file changes, not the code.

    	[TestFixture]
    	public class SurveyTest {
    		Configuration cfg;
    		ISessionFactory factory;
    
    		[TestFixtureSetUp]
    		public void OneTimeSetUp() {
    			Console.Out.WriteLine("running "+MethodBase.GetCurrentMethod());
    			cfg = new Configuration();
    			cfg.AddAssembly("SDLite");
    			factory = cfg.BuildSessionFactory();
    		}
    		[TestFixtureTearDown]
    		public void OneTimeTearDown() {
    			Console.Out.WriteLine("running "+MethodBase.GetCurrentMethod());
    			cfg = null;
    			factory = null;
    		}
    
    		[Test]
    		public void Save() {
    			Console.Out.WriteLine("running "+MethodBase.GetCurrentMethod());
    			string name = "TestSurvey42";
    			Survey s = CreateSurvey(name,"TestGroup",10,1);
    		}
    		[Test]
    		public void Retrieve() {
    			Console.Out.WriteLine("running "+MethodBase.GetCurrentMethod());
    			string name = "TestSurveyRetrieve";
    			CreateSurvey(name,"TestGroup",10,1);
    
    			Survey s = GetSurvey(name);
    			Assert.IsNotNull(s);
    			Assert.AreEqual(s.Name,name);
    			Assert.AreEqual(s.GroupName,"TestGroup");
    			Assert.AreEqual(s.Priority,10);
    			Console.Out.WriteLine(s.ToString());
    		}
    		[Test]
    		public void Modify() {
    			Console.Out.WriteLine("running "+MethodBase.GetCurrentMethod());
    			string name = "TestSurveyModify";
    			CreateSurvey(name,"TestGroup",10,1);
    
    			Survey survey = GetSurvey(name);
    			survey.Priority = 5;
    			survey.Status = 0;
    			Console.Out.WriteLine(survey.ToString());
    			ISession session = factory.OpenSession();
    			//ITransaction transaction = session.BeginTransaction();
    			session.Update(survey);
    			//transaction.Commit();
    			session.Flush();
    			session.Close();
    			
    		}
    		/// <summary>
    		/// utility method to get a survey
    		/// </summary>
    		/// <param name="name">survey name</param>
    		/// <returns>survey object</returns>
    		public Survey GetSurvey(string name) {
    			ISession session = factory.OpenSession();
    			session = factory.OpenSession();
    			Survey s = (Survey)session.Load(typeof(Survey), name);
    			session.Close();
    			return s;
    		}
    		
    		
    		/// <summary>
    		/// If it already exists, it is deleted.
    		/// Then it is created.
    		/// </summary>
    		/// <param name="name">survey name</param>
    		public Survey CreateSurvey(string name, string groupName, int priority, int status) {
    			DeleteSurvey(name);
    			ISessionFactory factory = cfg.BuildSessionFactory();
    			ISession session = factory.OpenSession();
    			ITransaction transaction = session.BeginTransaction();
    			Survey survey = new Survey(name,groupName,priority,status);
    			//Console.Out.WriteLine(survey.ToString());
    			session.Save(survey);
    			transaction.Commit();
    			session.Close();
    			return survey;
    		}
    		/// <summary>
    		/// deletes the survey if it exists, if it does not exist, we exit quietly
    		/// </summary>
    		/// <param name="name">survey name</param>
    		public void DeleteSurvey(string name) {
    			ISessionFactory factory = cfg.BuildSessionFactory();
    			ISession session = factory.OpenSession();
    			Survey survey = (Survey)session.Get(typeof(Survey), name);
    			if(survey != null) {
    				ITransaction transaction = session.BeginTransaction();
    				session.Delete(survey);
    				transaction.Commit();
    				session.Close();
    			}
    		}
    	}
    
    
  6. View entire Survey.cs file.
  7. Recommended Books:
    Click to read reviews or buy Hibernate In Action
    by Christian Bauer and Gavin King
    Click to read reviews or buy Hibernate Quickly
    by Patrick Peak Nick Heudecker
  8. Links
    1. http://www.hibernate.org
    2. nhibernate.sourceforge.net
    3. Quick Start Guide
X
dreamhost.com