Java 带有exists 子句的休眠条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23519115/
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 with exists clause
提问by meliniak
I cannot find a solution to a problem that seems to be easy. Say there are 2 entity classes:
我找不到一个看似简单的问题的解决方案。假设有 2 个实体类:
class A {
Set<B> bs;
}
class B {
String text;
}
How to create a criteria query that returns all A's that contains at least one B entity which fulfills a given condition (like b.text = 'condition')?
如何创建一个条件查询,该查询返回包含至少一个满足给定条件的 B 实体的所有 A(如 b.text = 'condition')?
采纳答案by Lucia Manescau
I think this link can be useful: http://mikedesjardins.net/2008/09/22/hibernate-criteria-subqueries-exists/
我认为这个链接很有用:http: //mikedesjardins.net/2008/09/22/hibernate-criteria-subqueries-exists/
It contains the following example about how create n exists criteria:
它包含以下示例,说明如何创建 n 存在条件:
"What you're really trying to do is to obtain all Pizza Orders where an associated small pizza exists. In other words, the SQL query that you're trying to emulate is
“您真正想做的是获取存在关联小披萨的所有披萨订单。换句话说,您要模拟的 SQL 查询是
SELECT *
FROM PIZZA_ORDER
WHERE EXISTS (SELECT 1
FROM PIZZA
WHERE PIZZA.pizza_size_id = 1
AND PIZZA.pizza_order_id = PIZZA_ORDER.pizza_order_id)
The way that you do that is by using an “exists” Subquery, like this:
您这样做的方法是使用“存在”子查询,如下所示:
Criteria criteria = Criteria.forClass(PizzaOrder.class,"pizzaOrder");
DetachedCriteria sizeCriteria = DetachedCriteria.forClass(Pizza.class,"pizza");
sizeCriteria.add("pizza_size_id",1);
sizeCriteria.add(Property.forName("pizza.pizza_order_id").eqProperty("pizzaOrder.pizza_order_id"));
criteria.add(Subqueries.exists(sizeCriteria.setProjection(Projections.property("pizza.id"))));
List<pizzaOrder> ordersWithOneSmallPizza = criteria.list();
And voila, the result will contain two PizzaOrders!"
瞧,结果将包含两个 PizzaOrders!”