Java Hibernate 标准:在没有映射关联的情况下连接表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/720502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate criteria: Joining table without a mapped association
提问by Snukker
I'd like to use Hibernate's criteria api to formulate a particular query that joins two entities. Let's say I have two entities, Pet and Owner with a owner having many pets, but crucially that association is not mapped in the Java annotations or xml.
我想使用 Hibernate 的标准 api 来制定连接两个实体的特定查询。假设我有两个实体,Pet 和 Owner,一个拥有许多宠物的所有者,但至关重要的是,该关联并未映射到 Java 注释或 xml 中。
With hql, I could select owners that have a pet called 'fido' by specifying the join in the query (rather than adding a set of pets to the owner class).
使用 hql,我可以通过在查询中指定联接(而不是将一组宠物添加到所有者类)来选择拥有名为“fido”的宠物的所有者。
Can the same be done using hibernate criteria? If so how?
可以使用休眠标准来完成同样的事情吗?如果是这样怎么办?
Thanks, J
谢谢,J
采纳答案by David M
My understanding is that if you do this using HQL, you are creating a Cartesian join with a filter, rather than an inner join. Criteria queries do not support doing this.
我的理解是,如果您使用 HQL 执行此操作,您将使用过滤器创建笛卡尔连接,而不是内部连接。条件查询不支持这样做。
回答by tpdi
There's a SQLCriterion
, which you can give arbitrary SQL
, and add to your Criteria
. In the SQL
string, the token {alias} "will be replaced by the alias of the root entity."
有一个SQLCriterion
,您可以任意指定SQL
,并添加到您的Criteria
. 在SQL
字符串中,标记 {alias} “将被根实体的别名替换。”
回答by Stefan Steinegger
In NHibernate you can use subqueries which are defined as DetachedCriteria. Not sure if it works the same in Java, most probably it is the same:
在 NHibernate 中,您可以使用定义为 DetachedCriteria 的子查询。不确定它在 Java 中是否相同,很可能是相同的:
DetachedCriteria pets = DetachedCriteria.For<Pet>("pet")
.SetProjection(Projections.Property("pet.ownername"))
.Add(/* some filters */ );
session.CreateCriteria(typeof(Owner))
.Add(Subqueries.PropertyIn("name", pets);
Assumed that it is joined using the name of the owner.
假设它是使用所有者的名字加入的。
回答by Pierre Pretorius
This is indeed possible with criteria:
这确实可以通过标准实现:
DetachedCriteria ownerCriteria = DetachedCriteria.forClass(Owner.class);
ownerCriteria.setProjection(Property.forName("id"));
ownerCriteria.add(Restrictions.eq("ownername", "bob"));
Criteria criteria = getSession().createCriteria(Pet.class);
criteria.add(Property.forName("ownerId").in(ownerCriteria));
Update: This actually performs a sub-query instead of a join but it allows you to use Criteria on two entities that do not have a hibernate relationship defined.
更新:这实际上是执行子查询而不是连接,但它允许您在两个未定义休眠关系的实体上使用 Criteria。
回答by javasmith
Criterion ownerCriterion = Restrictions.sqlRestriction(SELECT ownerId FROM Owner WHERE ownerName ='bob');
Criteria criteria = getSession().createCriteria(Pet.class);
criteria.createCriteria("ownerId").add(ownerCriterion);