Java 休眠子查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1411287/
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 subquery
提问by Kees Kist
I have a problem in creating subqueries with Hibernate. Unfortunately the Subqueries class is almost entirely undocumented, so I have absolutely no clue how to convert the following SQL into a Hibernate Criteria:
我在使用 Hibernate 创建子查询时遇到问题。不幸的是 Subqueries 类几乎完全没有记录,所以我完全不知道如何将以下 SQL 转换为 Hibernate Criteria:
SELECT id
FROM car_parts
WHERE car_id IN ( SELECT id FROM cars WHERE owner_id = 123 )
I was hoping the following would 'just work':
我希望以下内容“有效”:
session.createCriteria(CarParts.class).add(eq("car.owner", myCarOwner));
but unfortunately it does not. So it seems I actually have to use the Subqueries class to create the Criteria. But I was unable to find a reasonable example though Google, so that leads me to asking it here.
但不幸的是它没有。所以看起来我实际上必须使用子查询类来创建条件。但是我无法通过谷歌找到一个合理的例子,所以这导致我在这里问它。
采纳答案by Tom van Zummeren
Try to create an alias for the "car" property before adding the eq expression like this:
在添加这样的 eq 表达式之前,尝试为“car”属性创建一个别名:
session.createCriteria(CarParts.class)
.createAlias("car", "c")
.add(eq("c.owner", myCarOwner));
回答by Tom van Zummeren
As first check the ORM configuration between Car and CarPart entities, usually you need the setup the relationship between them. After that try to execute the following code:
首先检查 Car 和 CarPart 实体之间的 ORM 配置,通常您需要设置它们之间的关系。之后尝试执行以下代码:
List result = session.createQuery("from " + CarPart.class.getName() +
" as parts join parts.car as car where car.owner = :myOwner")
.setParameter("myOwner", 123)
.list();
回答by Rohtash Singh
Try Like this:
试试这样:
Table details): Category (id, name, desc, parentId, active)
表详细信息):类别(id、name、desc、parentId、active)
DetachedCriteria subCriteria = DetachedCriteria
.forClass(Category.class);
subCriteria.add(Restrictions.isNull("parent"));
subCriteria.add(Restrictions.eq("active", Boolean.TRUE));
subCriteria.add(Restrictions.eq("name", categoryName));
subCriteria.setProjection(Projections.property("id"));
Criteria criteria = getSession().createCriteria(Category.class);
criteria.add(Restrictions.eq("active", Boolean.TRUE));
criteria.add(Subqueries.propertyEq("parent", subCriteria));
It will generate the query like:
它将生成如下查询:
select
*
from
Categories this_
where
this_.active=1
and this_.parentId = (
select
this0__.id as y0_
from
Categories this0__
where
this0__.parentId is null
and this0__.active=1
and this0__.name='Health Plan'
)
Good Luck!
祝你好运!
-Rohtash Singh
-罗塔什·辛格