views:

813

answers:

3

I'm a little confused about how to do something in HQL.

So let's say I have a class Foo that I'm persisting in hibernate. It contains a set of enum values, like so:

public class Foo
{
    @CollectionOfElements
    private Set<Bar> barSet = new HashSet<Bar>();

    //getters and setters here ...
}

and

public enum Bar
{
    A,
    B
}

Is there an HQL statement I can use to fetch only Foo instances who'se barSet containst Bar.B?

List foos = session.createQuery("from Foo as foo " +
"where foo.barSet.contains.Bar.B").list();

Or am I stuck fetching all Foo instances and filtering them out at the DAO level?

List foos = session.createQuery("from Foo as foo").list();

List results = new ArrayList();

for(Foo f : foos)
{
  if(f.barSet.contains(Bar.B))
    results.add(f);
}

Thanks!

+2  A: 

You should map as follows

@CollectionOfElements
@Enumerated(EnumType.STRING)
@JoinTable(
    name="BAR_TABLE",
    joinColumns=@JoinColumn(name="FOO_ID")
)
public Set<Bar> getBarSet() {
    return this.BarSet;
}

And your HQL looks like

select distinc Foo _foo inner join fetch _foo.barSet bar where bar = :selectedBar

query.setParameter("selectedBar", Bar.A);

query.list();

Here you can see how to map

regards,

Arthur Ronald F D Garcia
+1  A: 

You can do this

"from Foo as foo where :selectedBar member of foo.barSet"

Kevin
Thanks. I'll give this a shot.
Seth
This doesn't appear to be working ... can you point me to a tutorial on how to use "member of"?
Seth
A: 

I usually prefer storing enum sets as bitsets in the database. It's blazing fast and requires one (!) single column. I don't know how HQL handles bit operations but you can register your own.

Willi