Hibernate标准的多对多实体属性 [英] Hibernate criteria for many-to-many entity property

查看:170
本文介绍了Hibernate标准的多对多实体属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Entity
class A {

@ManyToMany
private List<B> list;
...
}

@Entity
class B {
...
}

我想使用标准(不是sql查询)从A类获取列表。这样做有可能吗?在这种情况下,投影不起作用。

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.

推荐答案

不幸的是,Criteria只允许选择根实体,而不是任何联合实体。如果你的ManyToMany是双向的,那么它会更容易。你可以使用相当于

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

如果这不是一个选项,我认为唯一的方法是使用子查询, to

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)

代码如下所示:

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

这篇关于Hibernate标准的多对多实体属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆