2009-11-04 130 views
2

我有三個表和2 JPA模型類:冬眠許多一對多

Unit 
------------ 
id [PK] - Integer 
code  - String 
unitGroups - List<UnitGroup> 


UnitGroup 
------------ 
id [PK] - Integer 
ugKey  - String 
units  - List<Unit> 

單元和unitGroups具有它們之間多到多的關係。 簡要我想寫一個HQL查詢來獲取以下SQL的輸出:

SELECT u.* 
FROM units u, unit_groups ug, unit_group_pairs ugp 
WHERE ugp.UnitID = u.ID 
AND ugp.UnitGroupID = ug.ID 
AND ug.UGKey = 'amount' AND u.ID = 10 

回答

1

select u from Unit u left join u.unitGroups ug where u.id = 10 and ug.ugKey = 'amount' 
1

我希望這會工作,但不能肯定。請不要否定:)。我沒有自己嘗試過。只是想出這個,所以它可能會幫助你。乾杯。

from Unit as units 
inner join fetch units.unitGroups grp 
inner join fetch grp.units 
where grp.ugKey = 'amount' and units.id = 10 
+0

謝謝,但我建立了許多-to-many關聯。我的問題是關於hql的。 – 2009-11-04 08:39:53

+0

已修改。對不起,錯誤的假設。 – 2009-11-04 11:07:11

+0

我得到這個錯誤; org.hibernate.loader.MultipleBagFetchException:無法同時獲取多個行李 – 2009-11-04 11:22:50

0

最後試試這個

select u from unit as u 
where u.ID = 10 and 
'amount' = any elements(u.unitGroups.UGKey) 
+0

從u單元中選擇u,其中u.id = 10且'amount'=任何元素(u.unitGroups.ugKey): org.hibernate.QueryException:非法嘗試使用元素屬性取消引用collection [unit0_.ID.unitGroups]參考[ugKey] – 2009-11-05 09:20:20