原文出处;http://www.cnblogs.com/abluedog/archive/2006/04/15/375862.html
原文作者: abluedog
最近在学NHibernate,从 abluedog处受益匪浅。但原文写的时间久了,当前有些组件早已升级换代,且有些地方有疏漏,导致编译的时候报错,所以我一边学习,一边更正。
基本的软件环境如下:
1.NHibernate  www.nhibernate.org 我下的是NHibernate-2.1.2.GA-bin.zip
2.Code Smith  http://www.codesmithtools.com/ 我用的是CodeSmith Professional v5.1.3.8510
3.NHibernate模板 点击这里下载 
4.  VS2008 +SQL2008
操作步骤:
1,建立并使用一个叫NHibernate的数据库,新建Person表,建表语句:
USE [NHibernate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Person](
        [id] [ int] IDENTITY(1,1) NOT NULL,
        [ name] [ varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED    
(
        [id] ASC
) WITH (IGNORE_DUP_KEY = OFF) ON [ PRIMARY]
) ON [ PRIMARY]

GO
SET ANSI_PADDING OFF
仅有两个字段,一个自动增长的id,一个name,这不需要多解释了。
 
2,下载的nhibernate-template解压,打开Code Smith,新建个目录,把解压的nhibernate-template文件全部复制进去,这样就将模板加入”Template Explorer”。
如图:
右键点击NHibernate.cst,选择“Execute”,弹出设置窗口,在左边的属性窗口进行如下设置。NHibernate.cst会生成类文件和相应的XML配置文件。Outputdirectory是这2个文件的保存路径。
 
SourceDatabase属性在第一次选择时需要配置一个连接字符串,如何建立连接字符串见上图,注意的是provider type 选择SqlschemaProvider,配置好后Code Smith将记录下来。 Assembly属性代表的是生成文件的默认Assembly名,而NameSpace,就是使用的命名空间了,这里我们全部使用”Test.Model”,点击左下角的Generate,将会在指定的输出目录下产生两个文件:Person.cs,Person.hbm.xml。
这样,NHibernate需要的类文件和映射文件生成完了。
 
3, 新建立一个类库工程,为了简洁起见,我们命名为Model,需要注意的是,为了跟刚才生成的文件对应,我们需要在Model工程的属性页中将起Assembly和命名空间名字设为上面的“Test.Model”。
然后将刚才生成的两个文件Person.cs和Person.hbm.xml加入到Model工程中来,选中Person.hbm.xml文件,在属性窗口中将其“Build Action”设置为“Embedded Resource”(这是非常重要的一步,否则NHibernate将无法找到映射文件)。
注意:这里要修改下生成的Person.cs,Id和Name两个属性前要加Virtual字段。具体代码:
InBlock.gif using System;
InBlock.gif using System.Collections;
InBlock.gif
InBlock.gif namespace Test.Model
InBlock.gif{
InBlock.gifPerson #region Person
InBlock.gif
InBlock.gif   /// <summary>
InBlock.gif   /// Person object for NHibernate mapped table 'Person'.
InBlock.gif   /// </summary>
InBlock.gif   public class Person
InBlock.gif  {
InBlock.gifMember Variables #region Member Variables
InBlock.gif    
InBlock.gif     protected int _id;
InBlock.gif     protected string _name;
InBlock.gif
InBlock.gif    #endregion
InBlock.gif
InBlock.gifConstructors #region Constructors
InBlock.gif
InBlock.gif     public Person() { }
InBlock.gif
InBlock.gif     public Person( string name )
InBlock.gif    {
InBlock.gif       this._name = name;
InBlock.gif    }
InBlock.gif
InBlock.gif    #endregion
InBlock.gif
InBlock.gifPublic Properties #region Public Properties
InBlock.gif
InBlock.gif                 public virtual int Id
InBlock.gif    {
InBlock.gif      get { return _id;}
InBlock.gif      set {_id = value;}
InBlock.gif    }
InBlock.gif
InBlock.gif                 public virtual string Name
InBlock.gif    {
InBlock.gif      get { return _name; }
InBlock.gif      set
InBlock.gif      {
InBlock.gif         if ( value != null && value.Length > 50)
InBlock.gif           throw new ArgumentOutOfRangeException( "Invalid value for Name", value, value.ToString());
InBlock.gif        _name = value;
InBlock.gif      }
InBlock.gif    }
InBlock.gif
InBlock.gif    
InBlock.gif
InBlock.gif    #endregion
InBlock.gif  }
InBlock.gif  #endregion
InBlock.gif}
另外,Person.hbm.xml代码:
<? xml version ="1.0" encoding ="utf-8" ?>
< hibernate-mapping xmlns ="urn:nhibernate-mapping-2.2" >
   < class name ="Test.Model.Person, Test.Model" table ="Person" >
     < id name ="Id" type ="Int32" unsaved-value ="null" >
       < column name ="id" length ="4" sql-type ="int" not-null ="true" unique ="true" index ="PK_Person" />
       < generator class ="native" />
     </ id >
     < property name ="Name" type ="String" >
       < column name ="name" length ="50" sql-type ="varchar" not-null ="true" />
     </ property >
   </ class >
</ hibernate-mapping >
这里要注意 xmlns="urn:nhibernate-mapping- 2.2"
 
 
4,建立一个控制台工程,命名为Console1,添加NHibernate(包括Antlr3.Runtime.dll;NHibernate.dll;NHibernate.ByteCode.Castle.dll)和上面Model项目的引用,另外添加一个应用程序配置文件(application  configuration file),App.config的具体配置如下:
<? xml version ="1.0" encoding ="utf-8" ?>
< configuration >
    <!-- Add this element -->
     < configSections >
         < section name ="hibernate-configuration" type ="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
     </ configSections >
    <!-- Add this element -->
     < hibernate-configuration xmlns ="urn:nhibernate-configuration-2.2" >
         < session-factory >
             < property name ="dialect" >NHibernate.Dialect.MsSql2008Dialect </ property >
             < property name ="connection.provider" >NHibernate.Connection.DriverConnectionProvider </ property >
             < property name ="connection.connection_string" >Server=.;initial catalog=NHibernate;Integrated Security=SSPI </ property >
             < property name ="proxyfactory.factory_class" >NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle </ property >
         </ session-factory >
     </ hibernate-configuration >
    <!-- Leave the system.web section unchanged -->
     < system.web >
     </ system.web >
</ configuration >
 
5,console1项目中的program.cs文件:
InBlock.gif using System;
InBlock.gif using System.Collections.Generic;
InBlock.gif using System.Text;
InBlock.gif using NHibernate;
InBlock.gif using NHibernate.Cfg;
InBlock.gif using Test.Model;
InBlock.gif
InBlock.gif namespace Console1
InBlock.gif{
InBlock.gif         class Program
InBlock.gif        {
InBlock.gif                 static void Main( string[] args)
InBlock.gif                {
InBlock.gif                        Configuration config = new Configuration().AddAssembly( "Test.Model");
InBlock.gif                        ISessionFactory factory = config.BuildSessionFactory();
InBlock.gif                        ISession session = factory.OpenSession();
InBlock.gif
InBlock.gif                        Person person = new Person();
InBlock.gif                        person.Name = "Jackie Chan";
InBlock.gif
InBlock.gif                        ITransaction trans = session.BeginTransaction();
InBlock.gif                         try
InBlock.gif                        {
InBlock.gif                                session.Save(person);
InBlock.gif                                trans.Commit();
InBlock.gif                                Console.WriteLine( "Insert Success!");
InBlock.gif                        }
InBlock.gif                         catch (Exception ex)
InBlock.gif                        {
InBlock.gif                                trans.Rollback();
InBlock.gif                                Console.WriteLine(ex.Message);
InBlock.gif                        }
InBlock.gif                }
InBlock.gif        }
InBlock.gif}
 
7,编译console1,
数据库检查一下,我们想要添加的记录已经成功加入到数据库中!!