手把手構建首個 NHibernate 專案:經典 Customer/Order/Product 電商場景,採用三層架構,完成 Customer 表映射與數據讀取驗證。
下載 NHibernate-2.0.1.GA,引用核心程序集:NHibernate.dll、Iesi.Collections.dll、log4net.dll 等。
創建 NHibernateSample 資料庫,執行腳本建立四張表:
NHibernateSample.sln
├── lib/ # NHibernate 相關 DLL
├── DomainModel/ # 領域模型層
│ ├── Entities/ # 持久化類
│ └── Mappings/ # .hbm.xml 映射文件
├── DAL/ # 數據訪問層
│ └── SessionManager.cs # Session 工廠單例
└── DAL.Test/ # 測試項目 (NUnit)
└── hibernate.cfg.xml # NHibernate 配置
namespace DomainModel.Entities
{
public class Customer
{
public virtual int CustomerId { get; set; }
public virtual string Firstname { get; set; }
public virtual string Lastname { get; set; }
}
}
規則:
virtual 支援動態代理(延遲加載)sealed 類<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="DomainModel" namespace="DomainModel">
<class name="DomainModel.Entities.Customer,DomainModel" table="Customer">
<id name="CustomerId" column="CustomerId" type="Int32" unsaved-value="0">
<generator class="native" />
</id>
<property name="Firstname" column="Firstname" type="string" length="50" />
<property name="Lastname" column="Lastname" type="string" length="50" />
</class>
</hibernate-mapping>
關鍵設置:XML 文件「生成操作」必須設為 嵌入的資源,否則運行時找不到映射拋出 MappingException。
將 NHibernate 目錄下 configuration.xsd、nhibernate-mapping.xsd 複製到 VS Schema 目錄,獲得映射文件 IntelliSense。
public class SessionManager
{
private ISessionFactory _sessionFactory;
public SessionManager()
{
_sessionFactory = GetSessionFactory();
}
private ISessionFactory GetSessionFactory()
{
return new Configuration().Configure().BuildSessionFactory();
}
public ISession GetSession()
{
return _sessionFactory.OpenSession();
}
}
設計要點:ISessionFactory 線程安全、全局單例、僅初始化一次;ISession 非線程安全、單位工作、用完關閉。
public class NHibernateSample
{
private ISession _session;
public NHibernateSample(ISession session)
{
_session = session;
}
public Customer GetCustomerById(int customerId)
{
return _session.Get<Customer>(customerId);
}
}
<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">
Data Source=.\SQLEXPRESS;Initial Catalog=NHibernateSample;Integrated Security=True;Pooling=False
</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="show_sql">true</property>
<property name="adonet.batch_size">10</property>
<mapping assembly="DomainModel"/>
</session-factory>
</hibernate-configuration>
關鍵:配置文件「複製到輸出目錄」設為 始終複製,否則運行時 FileNotFoundException。
[TestFixture]
public class NHibernateSampleFixture
{
private ISession _session;
private SessionManager _helper;
private NHibernateSample _sample;
[TestFixtureSetUp]
public void TestFixtureSetup() => _helper = new SessionManager();
[SetUp]
public void Setup()
{
_session = _helper.GetSession();
_sample = new NHibernateSample(_session);
}
[Test]
public void GetCustomerByIdTest()
{
Customer customer = _sample.GetCustomerById(1);
Assert.AreEqual(1, customer.CustomerId);
}
}
TestDriven.NET 執行測試通過,輸出 SQL:
SELECT customer0_.CustomerId as CustomerId3_0_,
customer0_.Firstname as Firstname3_0_,
customer0_.Lastname as Lastname3_0_
FROM Customer customer0_ WHERE customer0_.CustomerId=@p0; @p0 = '1'
完成最小可行 NHibernate 專案,驗證核心流程:
此為後續所有進階主題(關係映射、查詢、加載、事務、並發)的基石。下篇將介紹 HQL 查詢語言。