繼 HQL 後,本文深入講解 NHibernate 第二大查詢方式——Criteria API:類型安全、動態構建、智能提示友好,支援關聯查詢、投影、聚合、離線查詢等高級特性。
public IList<Customer> CreateCriteria()
{
ICriteria crit = _session.CreateCriteria(typeof(Customer));
crit.SetMaxResults(50); // 限制最大結果集
return crit.List<Customer>();
}
ISession 為 Criteria 工廠,SetMaxResults 等同 SQL TOP/LIMIT。
public IList<Customer> Narrowing()
{
return _session.CreateCriteria(typeof(Customer))
.Add(Restrictions.Like("Firstname", "YJing%"))
.Add(Restrictions.Between("Lastname", "A%", "Y%"))
.List<Customer>();
}
Restrictions 提供豐富運算符:Eq/Ne/Gt/Ge/Lt/Le/Like/In/Between/IsNull/And/Or/Not 等。
public IList<Customer> Order()
{
return _session.CreateCriteria(typeof(Customer))
.Add(Restrictions.Like("Firstname", "Y%"))
.AddOrder(new Order("Firstname", false)) // false=DESC
.AddOrder(new Order("Lastname", true)) // true=ASC
.List<Customer>();
}
CreateCriteria("關聯屬性") 導航SetProjection(Projections...)DetachedCriteria 無 Session 構建,後綁定執行(2.0 新增)Subqueries 工廠方法根據示例對象自動生成查詢條件:
public IList<Customer> Query()
{
Customer sample = new Customer { Firstname = "YJing", Lastname = "Lee" };
return _session.CreateCriteria(typeof(Customer))
.Add(Example.Create(sample))
.List<Customer>();
}
public IList<Customer> UseQueryByExample_GetCustomer(Customer sample)
{
Example example = Example.Create(sample)
.IgnoreCase() // 忽略大小寫
.EnableLike() // 啟用模糊匹配
.SetEscapeCharacter('&'); // 設置轉義字符
return _session.CreateCriteria(typeof(Customer))
.Add(example)
.List<Customer>();
}
public IList<Customer> GetCustomersByFirstnameAndLastname(string firstname, string lastname)
{
return _session.CreateCriteria(typeof(Customer))
.Add(Restrictions.Eq("Firstname", firstname))
.Add(Restrictions.Eq("Lastname", lastname))
.List<Customer>();
}
// 測試:斷言查詢 "YJing"/"Lee" 結果數為 1
[Test]
public void GetCustomerByFirstnameAndLastnameTest()
{
var customers = _queryCriteriaAPI.GetCustomersByFirstnameAndLastname("YJing", "Lee");
Assert.AreEqual(1, customers.Count);
}
public IList<Customer> GetCutomersWithIdGreaterThan(int customerId)
{
return _session.CreateCriteria(typeof(Customer))
.Add(Restrictions.Gt("CustomerId", customerId))
.List<Customer>();
}
Criteria API 以強類型、動態構建、IDE 友好著稱,特別適合:
QBE 為簡單精確匹配提供極簡語法。下篇將講解 HQL 基礎語法與參數化技巧。