首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

NHibernate實戰(2):從零構建第一個 NHibernate 程序

     編輯:關於.NET

前言

手把手構建首個 NHibernate 專案:經典 Customer/Order/Product 電商場景,採用三層架構,完成 Customer 表映射與數據讀取驗證。

開發環境

  • Visual Studio 2008 SP1
  • SQL Server 2008 Express
  • NHibernate 2.0.1.GA (2008-09-29 發布)
  • TestDriven.NET 單元測試

六步構建流程

1. 獲取 NHibernate

下載 NHibernate-2.0.1.GA,引用核心程序集:NHibernate.dll、Iesi.Collections.dll、log4net.dll 等。

2. 建立資料庫表

創建 NHibernateSample 資料庫,執行腳本建立四張表:

  • Customer (客戶)
  • Order (訂單)
  • OrderProduct (訂單產品中間表)
  • Product (產品)

3. 創建類庫專案結構

NHibernateSample.sln
├── lib/                    # NHibernate 相關 DLL
├── DomainModel/            # 領域模型層
│   ├── Entities/           # 持久化類
│   └── Mappings/           # .hbm.xml 映射文件
├── DAL/                    # 數據訪問層
│   └── SessionManager.cs   # Session 工廠單例
└── DAL.Test/               # 測試項目 (NUnit)
    └── hibernate.cfg.xml   # NHibernate 配置

專案引用關係

  • DomainModel → Iesi.Collections.dll
  • DAL → NHibernate.dll, Iesi.Collections.dll, DomainModel
  • DAL.Test → NHibernate.dll, Iesi.Collections.dll, nunit.framework.dll, DomainModel, DAL

4. 編寫領域模型層

4-1 持久化類 (POCO 模式)

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 類
  • 提供公共無參構造函數
  • 訪問修飾符可為 public/protected/internal/private

4-2 映射文件

<?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。

VS 智能提示配置

將 NHibernate 目錄下 configuration.xsd、nhibernate-mapping.xsd 複製到 VS Schema 目錄,獲得映射文件 IntelliSense。

5. 編寫數據訪問層

5-1 SessionManager 單例工廠

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 非線程安全、單位工作、用完關閉。

5-2 業務操作類

public class NHibernateSample
{
    private ISession _session;
    
    public NHibernateSample(ISession session)
    {
        _session = session;
    }
    
    public Customer GetCustomerById(int customerId)
    {
        return _session.Get<Customer>(customerId);
    }
}

6. 編寫測試與配置

6-1 hibernate.cfg.xml 配置

<?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。

6-2 NUnit 測試驗證

[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 專案,驗證核心流程:

  1. 建表 → 持久化類 → 映射文件(三位一體)
  2. SessionFactory 單例 → Session 工作單元
  3. 配置文件嵌入資源 + 複製輸出
  4. NUnit 驗證基礎查詢

此為後續所有進階主題(關係映射、查詢、加載、事務、並發)的基石。下篇將介紹 HQL 查詢語言。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved