问题
@Entity
class A {
@ManyToMany
private List<B> list;
...
}
@Entity
class B {
...
}
I'd like to get list from A class using criteria (not sql query). Is it posible to do this? Projection in this case does not work.
回答1:
Unfortunately, The Criteria only allows selecting the root entity, and not any joined entity. It would thus be easier if your ManyToMany was bidirectional. You could the use the criteria equivalent of
select b from B b inner join b.as a where a = :theA
If that's not an option, I think the only way is to use a subquery, and thus code the criteria equivalent to
select b from B b where b.id in (select b2.id from A a inner join a.list b2 where a.id = :theAId)
The code would thus look like this:
Criteria c = session.createCriteria(B.class, "b");
DetachedCriteria dc = DetachedCriteria.forClass(A.class, "a");
dc.createAlias("a.list", "b2");
dc.add(Restrictions.eq("a.id", theA.getId()));
dc.setProjection(Projections.property("b2.id"));
c.add(Subqueries.propertyIn("b.id", dc));
回答2:
you should be able to call (assuming a is instance of A)
a.getList();
If the A class has been set up with appropriate getter setter. I don't see the need for Criteria query.
来源:https://stackoverflow.com/questions/8533466/hibernate-criteria-for-many-to-many-entity-property