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

NHibernate實戰(14):輕鬆掌握視圖映射與查詢

     編輯:關於.NET

前言

資料庫操作除表之外,視圖與存儲過程同樣重要。本文演示如何在 NHibernate 中映射與使用視圖,過程簡單直觀,打破視圖映射的神秘感。

實戰步驟

1. 建立資料庫視圖

在資料庫中創建 viewCustomer 視圖,選取欄位:CustomerId、Firstname、Lastname、OrderId、OrderDate。

2. 編寫持久化類

視圖唯讀特性,屬性 Setter 設為 private:

namespace DomainModel.Entities
{
    public class CustomerView
    {
        public virtual int CustomerId { get; private set; }
        public virtual string Firstname { get; private set; }
        public virtual string Lastname { get; private set; }
        public virtual int OrderId { get; private set; }
        public virtual DateTime OrderDate { get; private set; }
    }
}

3. 編寫映射文件

關鍵點:table="viewCustomer" 指定視圖名,mutable="false" 標記唯讀:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    assembly="DomainModel" namespace="DomainModel">

<class name="DomainModel.Entities.CustomerView,DomainModel"
    table="viewCustomer" mutable="false" >
    <id name="CustomerId" column="CustomerId" type="Int32">
        <generator class="native" />
    </id>
    <property name="Firstname" column="Firstname" type="string" />
    <property name="Lastname" column="Lastname" type="string" />
    <property name="OrderId" column="OrderId" type="Int32" />
    <property name="OrderDate" column="OrderDate" type="DateTime" />
</class>
</hibernate-mapping>

4. 資料訪問層查詢方法

使用 Criteria API 查詢指定日期後的訂單客戶:

public IList<CustomerView> GetCustomerView(DateTime orderDate)
{
    return _session.CreateCriteria(typeof(CustomerView))
        .Add(Restrictions.Gt("OrderDate", orderDate))
        .List<CustomerView>();
}

5. 單元測試驗證

[Test]
public void GetCustomerViewTest()
{
    DateTime testorderDate = new DateTime(2008, 10, 1);
    IList<CustomerView> customers = _relation.GetCustomerView(testorderDate);
    foreach (CustomerView view in customers)
    {
        Assert.GreaterOrEqual(view.OrderDate, testorderDate);
    }
}

6. 生成 SQL 驗證

SELECT this_.CustomerId as CustomerId0_0_,
    this_.Firstname as Firstname0_0_,
    this_.Lastname as Lastname0_0_,
    this_.OrderId as OrderId0_0_,
    this_.OrderDate as OrderDate0_0_
FROM viewCustomer this_
WHERE this_.OrderDate > @p0; @p0 = '2008/10/1 0:00:00'

結語

視圖映射與表映射幾乎一致,核心差異在於:

  • 持久化類屬性 Setter 設為 private 實現唯讀
  • 映射文件添加 mutable="false" 標記
  • 無需處理增刪改操作

掌握此技巧,即可在 NHibernate 中靈活運用視圖簡化複雜查詢邏輯。下篇將挑戰更具挑戰性的存儲過程應用。

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