hibernate criteria with exists clause

可紊 提交于 2019-12-03 08:40:06

问题


I cannot find a solution to a problem that seems to be easy. Say there are 2 entity classes:

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')?


回答1:


I think this link can be useful: http://mikedesjardins.net/2008/09/22/hibernate-criteria-subqueries-exists/

It contains the following example about how create n exists criteria:

"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

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!"



来源:https://stackoverflow.com/questions/23519115/hibernate-criteria-with-exists-clause

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