資料庫操作除表之外,視圖與存儲過程同樣重要。本文演示如何在 NHibernate 中映射與使用視圖,過程簡單直觀,打破視圖映射的神秘感。
在資料庫中創建 viewCustomer 視圖,選取欄位:CustomerId、Firstname、Lastname、OrderId、OrderDate。
視圖唯讀特性,屬性 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; }
}
}
關鍵點: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>
使用 Criteria API 查詢指定日期後的訂單客戶:
public IList<CustomerView> GetCustomerView(DateTime orderDate)
{
return _session.CreateCriteria(typeof(CustomerView))
.Add(Restrictions.Gt("OrderDate", orderDate))
.List<CustomerView>();
}
[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);
}
}
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 中靈活運用視圖簡化複雜查詢邏輯。下篇將挑戰更具挑戰性的存儲過程應用。