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!
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,
You can do this
"from Foo as foo where :selectedBar member of foo.barSet"
select mother from Cat as mother, Cat as kit where kit in elements(foo.kittens)
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.
来源:https://stackoverflow.com/questions/2403121/collection-containsenum-value-in-hql