Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subquery in where clause with CriteriaQuery

Can anybody give me some hints on how to put that kind of subquery in a CriteriaQuery? (I'm using JPA 2.0 - Hibernate 4.x)

SELECT a, b, c FROM tableA WHERE a = (SELECT d FROM tableB WHERE tableB.id = 3) - the second select will always get a single result or null.

like image 359
artaxerxe Avatar asked May 24 '13 11:05

artaxerxe


People also ask

How do you add subquery criteria?

In the first step, I instantiate a CriteriaQuery which returns Author entities. Then I call the subquery method on the CriteriaQuery to create a subquery that counts the Books written by the Author which is selected by the outer query. As you can see, I define the subquery in the same way as I create a CriteriaQuery.

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.

How can we add criteria to a SQL query?

In the query design grid, click the Criteria row of the field where you want to add the criterion.

How do you write a subquery in Java?

Subqueries must be surrounded by parentheses. Subqueries may contain EXISTS, ALL, and ANY expressions. EXISTS expressions: The [NOT] EXISTS expression is used with a subquery and is true only if the result of the subquery consists of one or more values and is false otherwise.


1 Answers

Try something like the following example to create a subquery:

CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);
Root tableA = cq.from(TableA.class);

Subquery<String> sq = cq.subquery(TableB.class);
Root tableB = cq.from(TableB.class);
sq.select(tableB.get("d"));
sq.where(cb.equal(tableB.get("id"), 3));

cq.multiselect(
    cb.get("a"),
    cb.get("b"),
    cb.get("c"));
cq.where(cb.equal(tableA.get("a"), sq));
List<Object[]> = em.createQuery(cq).getResultList();

Note the code has not been tested due to the lack of an IDE nearby.

like image 97
Menno Avatar answered Sep 28 '22 19:09

Menno