Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate criteria with exists clause

Tags:

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

like image 838
meliniak Avatar asked May 07 '14 13:05

meliniak


People also ask

How do you add subquery criteria?

Below is the pseudo-code for using sub-query using Criteria API. CriteriaBuilder criteriaBuilder = entityManager. getCriteriaBuilder(); CriteriaQuery<Object> criteriaQuery = criteriaBuilder. createQuery(); Root<EMPLOYEE> from = criteriaQuery.

Can you explain criteria in hibernate?

Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.

How do you write a subquery in HQL?

A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed. Note that HQL subqueries can occur only in the select or where clauses.


1 Answers

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

like image 83
Lucia Manescau Avatar answered Oct 11 '22 05:10

Lucia Manescau