2011-08-25 78 views
1

假設我有3個表格GrandCat,Cat和Kitt。他們有一對多的關係,所以我有以下類。所有關聯都是延遲加載。休眠什麼是加載對象圖的正確方法

GrandCat{ 
    int age; 
    Set<Cat> cats; 
} 

Cat{ 
    int age; 
    Set<kitt> kitten; 
    GrandCat grandCat; 
} 

Kit{ 
    String color; 
    Cat cat; 
} 

我想建立一個grandCat的列表。條件是grandCat.age> 10和Cat.age> 5並且至少有一個顏色爲黃色的kitt。當我做grandCat.getCats()時,只有貓滿足條件返回。例如,我有以下貓。這樣

grand 1(age>10)--> alex(age>5) ---> a(yellow),b,c    | 
       | 
       --> bob(age<5) --->d,e(yellow) 

grand 2(age>10) --> charlie(age<5) ---> f,g(yellow) 
        | 
        --> david(age>5)--->h 
        | 
        -->edward(age>5)-->j(yellow) 
        | 
        -->fay(age>5) --> i(yellow),k(yellow) 

other grandCats........ 

我想有回報GrandCats 關係是盛大1個grand2這樣

grand1-->alex-->a 
    grand2-->edward-->j 
      | 
      -->fay-->i,k 

他們grandcat,貓,小貓的millons,所以不希望加載他們然後過濾。

我知道我可以通過使用

select g,c,k from grandCat g inner join fetch g.cat c inner join fetch c.kitten k where g.age>10 and c.age>5 and k.color='yellow'. 

,然後循環返回值,看看哪些貓實現它屬於哪個grandCat和小貓貓。但這有一些缺點,在grandcat和cat級別上有重複。因爲他們返回爲

grand1-->alex-->a 
    grand2-->edward-->j 
    grand2-->fay-->i   
    grand2-->fay-->k 

所以我需要比較他們和過濾器,當有很多記錄時,這需要時間和消耗資源。 任何人都有一個很好的方式來加載?我應該使用3 hql嗎?首先得到匹配grandCat1和grand2

select g from grandCat g inner join fetch g.cat c inner join fetch c.kitten k where g.age>10 and c.age>5 and k.color='yellow'. 

然後用從去年的查詢grandcat返回查詢的貓,然後把貓grand.setcats()

select c from Cat c inner join fetch cat.grandCat g inner join fetch c.kitten k where g=:grandCat and c.age>5 and k.color='yellow' 

然後查詢小貓,做同樣的事情?

select k from Kitt k inner join fetch k.cat c where c=:cat and k.color='yellow' 

它似乎很單調。

這樣做的最好方法是什麼?順便說一下,我希望返回的grandCat及其「貓和小貓」仍然具有延遲加載能力,比如說小貓有其他關聯,我可以稍後通過延遲加載來使用它們。

回答

0
select distinct g from GrandCat g 
inner join fetch g.cat c 
inner join fetch c.kitten k 
where g.age>10 
and c.age>5 
and k.color='yellow' 

應該很好。返回的Grandcat只會在其貓集合中包含想要的貓,並且每隻貓只會在其小貓集合中擁有想要的小貓。

請注意,雖然Hibernate返回實體,但這些實體並不反映關聯的實際情況。我會將它們視爲只讀對象,而不是試圖以任何方式修改關聯,因爲它可能會產生災難性的副作用。

+0

我相信這會返回滿意的grandCats,但是當你做grandcat.getCats()時,所有來自這個grandcat的貓都會返回,無論它小於5歲,並且沒有任何黃色的kitt – Nan

+0

爲什麼你不嘗試一下? –

+0

我前幾天問過這個問題,真的做了測試。 http://stackoverflow.com/questions/7164606/hibernate-hql-how-to-get-matched-child-from-parent – Nan

相關問題