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

NHibernate實戰(4):Criteria API 條件查詢完全指南

     編輯:關於.NET

前言

繼 HQL 後,本文深入講解 NHibernate 第二大查詢方式——Criteria API:類型安全、動態構建、智能提示友好,支援關聯查詢、投影、聚合、離線查詢等高級特性。

NHibernate 三大查詢方式定位

  • HQL:面向對象 SQL,靜態字符串,功能最全
  • Criteria API:動態構建、編譯時檢查、適合條件可變搜索
  • 原生 SQL:完全控制、存儲過程、特定資料庫特性
  • QBE (Query By Example):Criteria API 特例,根據實例對象自動構建查詢條件

Criteria API 核心用法

1. 創建 ICriteria 實例

public IList<Customer> CreateCriteria()
{
    ICriteria crit = _session.CreateCriteria(typeof(Customer));
    crit.SetMaxResults(50); // 限制最大結果集
    return crit.List<Customer>();
}

ISession 為 Criteria 工廠,SetMaxResults 等同 SQL TOP/LIMIT。

2. 結果集限制

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

3. 結果集排序

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>();
}

4. 進階特性預覽

  • 關聯查詢/動態抓取:CreateCriteria("關聯屬性") 導航
  • 投影/聚合/分組:SetProjection(Projections...)
  • 離線查詢:DetachedCriteria 無 Session 構建,後綁定執行(2.0 新增)
  • 子查詢:Subqueries 工廠方法

Query By Example (QBE) 詳解

根據示例對象自動生成查詢條件:

基礎用法

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 基礎語法與參數化技巧。

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