views:

798

answers:

3

Hi,

i have three tables and 2 JPA model classes:

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


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

units and unitGroups have many-to-many relationship between themselves. briefly i want to write an HQL query to get the output of following 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  A: 

I hope this will work, but not sure. Please no negatives :). I haven't tried this out myself. Just come up with this, so it might help you. Cheers.

from Unit as units 
inner join fetch units.unitGroups grp
inner join fetch grp.units
where grp.ugKey = 'amount' and units.id = 10
Adeel Ansari
Thanks but i established the Many-to-many association. My question is about hql.
Fırat KÜÇÜK
Modified. Sorry for the wrong assumption.
Adeel Ansari
i got this error;org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags
Fırat KÜÇÜK
i found a solution like this:select (select u.id from Unit u where u.id = 10) from UnitGroup ug where ug.ugKey = 'amount'
Fırat KÜÇÜK
i noticed it's not a solution :) it also works on not "amount" situations.
Fırat KÜÇÜK
A: 

Try this

select u from  unit as u 
where u.ID = 10 and 
'amount' = any elements(u.unitGroups.UGKey)
non sequitor
select u from Unit u where u.id = 10 and 'amount' = any elements(u.unitGroups.ugKey):org.hibernate.QueryException: illegal attempt to dereference collection [unit0_.ID.unitGroups] with element property reference [ugKey]
Fırat KÜÇÜK
A: 

at last:

select u from Unit u left join u.unitGroups ug where u.id = 10 and ug.ugKey = 'amount'
Fırat KÜÇÜK