Hibernate criteria for many-to-many entity property

为君一笑 提交于 2019-12-09 18:58:50

问题


@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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!