2011-03-25 112 views
19

我在「hibernate in action」一書中看到以下語句。任何人都可以告訴我如何在運行時覆蓋策略。你可以做相反的方式,那就是我將策略集設置爲false,並且我想將它設置爲true? 「如何覆蓋運行時的休眠提取策略

」延遲提取允許您決定在第一個數據庫命中加載多少對象圖,以及哪些關聯僅在第一次訪問 時才應加載。延遲提取是對象持久性和達到可接受性能的第一步中的基本概念。 我們建議,首先,在映射文件中爲所有關聯進行懶惰配置(或者可能是批量延遲配置爲 )。 這種策略然後可以通過強制渴望獲取發生查詢在運行時覆蓋 。」

回答

30

如果您使用HQL爲您查詢,您可以指定你的渴望使用取‘取’關鍵字,像這樣:

from Cat as cat 
    inner join fetch cat.mate 
    left join fetch cat.kittens child 
    left join fetch child.kittens 

如果您正在使用的條件查詢API,您可以使用調用setFetchMode

List cats = sess.createCriteria(Cat.class) 
    .add(Restrictions.like("name", "Fritz%")) 
    .setFetchMode("mate", FetchMode.EAGER) 
    .setFetchMode("kittens", FetchMode.EAGER) 
    .list(); 
+3

似乎Hibernate不滿意添加「左連接提取」,除非目標實體在使用JPA2條件時出現在選擇列表中。如果添加root.fetch(「someChildProperty」)以請求左連接提取,它會產生錯誤「查詢指定的連接提取,但獲取的關聯的所有者不在選擇列表中」。 想法? JPA2似乎很難說「大部分時間都是懶洋洋的,但熱切地在這一個環境中」。 – 2012-06-20 08:55:40

+0

非常感謝!高度讚賞,安德魯! – 2014-04-09 10:46:59

-5

可能對您寫的東西像這樣使用LINQ提供程序的渴望查詢:

List<Customer> customers = session.Query<Customer>().Fetch(c => c.Orders).ToList(); 

這填補了所有獲取客戶的訂單在一個SQL查詢:

select 
    customer0_.CustomerId as CustomerId0_0_, 
    customer0_.ContactName as ContactN3_0_0_, 
    orders1_.CustomerId  as CustomerId0__, 
    orders1_.OrderId  as OrderId0__ 
    orders1_.OrderDate  as OrderDate3_1_, 
from Customers customer0_ 
    left outer join Orders orders1_ 
    on customer0_.CustomerId = orders1_.CustomerId 

你可以也取得孫子藏品(見here)。

+0

這是關於Java,而不是C# – vvondra 2016-01-11 16:29:27