2011-11-08 31 views
0

假設我有@Entity A,其中有一個@ManyToOne到@Entity B,並且這個B有一個惰性(默認)@OneToMany到一個名爲集合的集合「圖像」hql - 如何填充一個子實體的懶惰集合,當獲取父

我想要做的事,如:

"select a from A a join fetch a.b.images where a.b = :b" 

這是發現B的給定一個實例的實例查詢(在A - > B鏈接是單向的,從A)。 試圖像上面的方法登陸我休眠例外:

query specified join fetching, but the owner of the fetched association was not present in the select list 

而是試圖像

"select a, a.b.images from ..." 

將返回多個結果爲A的每個實例(乘以圖像數量)

我如何在填充abimages的A上編寫查詢?

回答

1

試試這個 - 你首先需要加入fetch a.b分配一個別名,然後加入fetch alias.images。查詢docs瞭解更多詳情。如果a.b和b.images都是一對多的話,這樣做不是一個好主意 - 它會導致結果集爆炸。像批量大小或子選擇一樣是優化它的更好方法。

"select a from A a join fetch a.b x join fetch x.images where a.b = :b"