nhibernate教程(4)--條件查詢(Criteria Query)

來源:互聯網
上載者:User

標籤:添加   cap   archive   結果   xtu   2.0   order   條件   http   

NHibernate之旅(4):探索查詢之條件查詢(Criteria Query)

2008-10-16 18:20 by 李永京, 44341 閱讀, 43 評論, 收藏,  編輯

本節內容

  • NHibernate中的查詢方法
  • 條件查詢(Criteria Query)
    • 1.建立ICriteria執行個體
    • 2.結果集限制
    • 3.結果集排序
    • 4.一些說明
  • 根據樣本查詢(Query By Example)
  • 執行個體分析
  • 結語

上一節,我們介紹了NHibernate查詢語言的一種:NHibernate查詢語言(HQL,NHibernate Query  Language),這一節介紹一下條件查詢(Criteria API)。

NHibernate中的查詢方法

在NHibernate中提供了三種查詢方式給我們選擇:NHibernate查詢語言(HQL,NHibernate Query  Language)、條件查詢(Criteria API,Criteria Query)、(根據樣本查詢(QBE,Query By Example)是條件查詢的一種特殊情況)、原生SQL(Literal SQL,T-SQL、PL/SQL)。每個人有不同的喜好和特長,可以根據自己的情況選擇使用其中的一種或幾種。這一節我們介紹條件查詢。

條件查詢(Criteria Query)

HQL極為強大,但是有些人希望能夠動態使用一種物件導向API建立查詢,而不是在.NET代碼中嵌入字串。在NHibernate中,提供了一種直觀的、可擴充的Criteria API。在我們鍵入查詢語句的時候,提供了編譯時間的語法檢查,VS提供了強大的智能提示。如果你對HQL的文法感覺不是很舒服的話,用這種方法可能更容易。這種API也比HQL更可擴充。

典型用法:從ISession介面中建立ICriteria執行個體對象;在這個ICriteria執行個體對象上設定一個或多個運算式;要求ICriteria介面返回需要的列表,就是根據運算式從資料庫中返回對象。

注意:由於篇幅有限,我在這裡僅僅貼出了資料訪問層的代碼。測試這些方法的代碼就沒有貼出來了,你可以下載本系列的原始碼仔細看看測試這些方法的代碼。這些執行個體我爭取寫出來可以運行起來,大家下載源碼看看效果,一些資料需要按個人資料庫裡的資料情況修改。例如查詢條件和結果。這節,我們在上一節原始碼的基礎上,在資料訪問層中建立QueryCriteriaAPI.cs類用於編寫條件查詢方法,在資料訪問的測試層建立一QueryCriteriaAPIFixture.cs類用於測試。

1.建立ICriteria執行個體

使用ISession介面的CreateCriteria方法建立了NHibernate.ICriteria介面一個特定的持久化類的查詢執行個體,也可以說ISession是用來製造Criteria執行個體的工廠。

public IList<Customer> CreateCriteria(){    ICriteria crit = _session.CreateCriteria(typeof(Customer));    crit.SetMaxResults(50);    IList<Customer> customers = crit.List<Customer>();    return customers;}

例如上面的例子返回Customer對象集合,設定最大的集合數量為50條。

2.結果集限制

使用ICriteria介面提供的Add方法添加Restrictions類中約束運算式可以限制一些結果集的作用。

public IList<Customer> Narrowing(){    IList<Customer> customers = _session.CreateCriteria(typeof(Customer))        .Add(Restrictions.Like("Firstname", "YJing%"))        .Add(Restrictions.Between("Lastname", "A%", "Y%"))        .List<Customer>();    return customers;}
3.結果集排序

使用ICriteria.Order對結果集排序,第二個參數true代表asc,false代表desc。例如下面例子查詢Customer對象按FirstName降序、Lastname升序。

public IList<Customer> Order(){    return _session.CreateCriteria(typeof(Customer))        .Add(Restrictions.Like("Firstname","Y%"))        .AddOrder(new NHibernate.Criterion.Order("Firstname", false))        .AddOrder(new NHibernate.Criterion.Order("Lastname", true))        .List<Customer>();}
4.一些說明

條件查詢同樣支援關聯查詢、動態關聯抓取(在介紹一對多,多對多關係中闡述),投影、彙總和分組,離線(detached)查詢和子查詢是2.0版新增加的內容,以後在相關知識中介紹。也可以自行參考NHibernate參考文檔13章。

根據樣本查詢(Query By Example)

根據樣本查詢(QBE,Query By Example)是條件查詢的一種特殊情況,NHibernate.Criterion.Example類根據你指定的執行個體創造查詢條件。其典型的用法:建立一個Example執行個體;在Example執行個體上設定值;根據Example和設定NHibernate返回其對象集合。

例如下面的例子,按照指定Customer查詢資料庫裡的記錄:

public IList<Customer> Query(){    Customer customerSample = new Customer() { Firstname = "YJing", Lastname = "Lee" };    return _session.CreateCriteria(typeof(Customer))        .Add(Example.Create(customerSample))        .List<Customer>();}

你可以自行調整Example使之更實用:

public IList<Customer> UseQueryByExample_GetCustomer(Customer customerSample){    Example example = Example.Create(customerSample)        .IgnoreCase()        .EnableLike()        .SetEscapeCharacter(‘&‘);    return _session.CreateCriteria(typeof(Customer))       .Add(example)       .List<Customer>();}
執行個體分析

執行個體1:利用CriteriaAPI按Firstname和Lastname查詢顧客。

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

測試:調用GetCustomersByFirstnameAndLastname方法,查詢Firstname為“YJing",Lastname為"Lee"的顧客,判斷查詢結果數量是否為1。(註:在資料庫中有符合這一個記錄)

[Test]public void GetCustomerByFirstnameAndLastnameTest(){    IList<Customer> customers =         _queryCriteriaAPI.GetCustomersByFirstnameAndLastname("YJing", "Lee");    Assert.AreEqual(1, customers.Count);}

執行個體2:利用CriteriaAPI擷取顧客ID大於CustomerId的顧客。

public IList<Customer> GetCutomersWithIdGreaterThan(int customerId){    return _session.CreateCriteria(typeof(Customer))        .Add(Restrictions.Gt("CustomerId", customerId))        .List<Customer>();}
結語

好了,通過2篇文章的介紹,對NHibernate中的查詢文法有了大致瞭解,知道了NHibernate中兩種最主要的查詢方式,還有一種原生SQL查詢,內容不多,請參考NHibernate官方文檔吧。多多練習!下節將介紹對對象的操作。

nhibernate教程(4)--條件查詢(Criteria Query)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.