原文出處;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模板 點擊這裏下載
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
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
}
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>
<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>
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>
<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);
}
}
}
}
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,
數據庫檢查一下,我們想要添加的記錄已經成功加入到數據庫中!!