Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a JPQL SubQuery?

Tags:

java

orm

jpa

jpql

It is possible to do the equivalent of this sql query in JPQL?

SELECT * 
 FROM COUNTRIES c WHERE COUNTRY_ID IN (
  SELECT DISTINCT COUNTRY_ID 
   FROM PORTS p 
   WHERE p.COUNTRY_ID = c.COUNTRY_ID AND STATE = 'A'
) 
like image 581
ErVeY Avatar asked Sep 02 '10 16:09

ErVeY


People also ask

Can we use subquery in JPQL?

A subselect is a query embedded into another query. It's a powerful feature you probably know from SQL. Unfortunately, JPQL supports it only in the WHERE clause and not in the SELECT or FROM clause. Subqueries can return one or multiple records and can use the aliases defined in the outer query.

How do you create a subquery query?

Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY.

How do you write a subquery in criteriaBuilder?

where(criteriaBuilder.in(path). value(subquery)); TypedQuery<Object> typedQuery = entityManager. createQuery(select); List<Object> resultList = typedQuery. getResultList();


1 Answers

You need to test it with IN and subquery since both do work in JPQL (according to syntax reference they do work together). You may also look at MEMBER OF expressions.

But there is a better approach in my opinion. Such queries are called correlated sub-queries and one can always re-write them using EXISTS:

SELECT * FROM COUNTRIES c WHERE 
EXISTS (
        SELECT 'found' FROM PORTS p 
        WHERE p.COUNTRY_ID = c.COUNTRY_ID AND STATE = 'A'
) 

JPQL supports EXISTS with subqueries.

like image 73
topchef Avatar answered Oct 05 '22 12:10

topchef