NHibernate Step by Step 学习笔记(一) Hello,NHibernate!

原文出处;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字段。具体代码:
using System;
using System.Collections;

namespace Test.Model
{
Person#region Person

  /// <summary>
  /// Person object for NHibernate mapped table 'Person'.
  /// </summary>
  public class Person
  {
Member Variables#region Member Variables
    
    protected int _id;
    protected string _name;

    #endregion

Constructors#region Constructors

    public Person() { }

    public Person( string name )
    {
      this._name = name;
    }

    #endregion

Public Properties#region Public Properties

                public virtual int Id
    {
      get {return _id;}
      set {_id = value;}
    }

                public virtual string Name
    {
      get { return _name; }
      set
      {
        if ( value != null && value.Length > 50)
          throw new ArgumentOutOfRangeException("Invalid value for Name", value, value.ToString());
        _name = value;
      }
    }

    

    #endregion
  }
  #endregion
}
另外,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文件:
using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using Test.Model;

namespace Console1
{
        class Program
        {
                static void Main(string[] args)
                {
                        Configuration config = new Configuration().AddAssembly("Test.Model");
                        ISessionFactory factory = config.BuildSessionFactory();
                        ISession session = factory.OpenSession();

                        Person person = new Person();
                        person.Name = "Jackie Chan";

                        ITransaction trans = session.BeginTransaction();
                        try
                        {
                                session.Save(person);
                                trans.Commit();
                                Console.WriteLine("Insert Success!");
                        }
                        catch (Exception ex)
                        {
                                trans.Rollback();
                                Console.WriteLine(ex.Message);
                        }
                }
        }
}
 
7,编译console1,
数据库检查一下,我们想要添加的记录已经成功加入到数据库中!!
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章