views:

132

answers:

1

Currently, I have an HQL query that returns all Members who possess ANY Award from a set of specified Awards:

from Member m left join m.awards as a where a.name in ("Trophy","Ribbon");

What I now need is HQL that will return all Members who possess ALL Awards specified in the set of Awards.

So, assuming this data:

Joe has Trophy, Medal
Sue has Trophy, Ribbon
Tom has Trophy, Ribbon, Medal

The query above would return Joe, Sue, and Tom because all three possess at least one of Trophy or Ribbon. But I need to return only Sue and Tom, because they are the only ones who possess all of the specified awards (Trophy and Ribbon).

Here's the class structure (simplified):

class Member {
  private String name;
  private Set<Award> awards;
}
class Award {
  private String name;
}
+2  A: 
select m from Member m left join m.awards as a where a.name in ("Trophy","Ribbon") group by m having count(a)=2
serg
@serg555 - Nice! Should it be count(a)=2 or count(2)>=2 ? Also, is there a way to do it without a group by/having clause? My actual query is quite complex and includes a where clause, order by clause, multiple subqueries and such. I also need to run the same query but with a count(*) to get the number of records returned. Running into trouble getting it all to work with the group by clause.
Tauren
It should be `count(a)=2`. Sorry, I don't know alternate solution without grouping.
serg
@serg555: ok, thanks. The problem I'm having is when I include group by/having in my count(*) query, I don't get a unique result. So countQuery.uniqueResult() fails. I need to get the total number of results for my pagination controls.
Tauren
You can add distinct to the query. `select distinct m from Member m ...` or `select count(distinct m.id) from ...`
serg
@serg555: That's exactly what I'm doing: `select count(distinct m.id) from ...`. But with the group by, `uniqueResults()` throws an exception. For instance, the regular query returns 4 member objects: `[Member, Member, Member, Member]`. The `count()` version of the query returns an array of 4 elements: `[1,1,1,1]`. I assume that is because each "group" has a size of 1. Any ideas?
Tauren
Sorry, not sure.
serg