Hibernate criteria for many-to-many entity property

荒凉一梦 提交于 2019-12-04 13:42:54

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));

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.

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