sura2k
sura2k

Reputation: 7517

JPQL JOINS with nested SELECT

Can I do something like this on JPQL?

SELECT NEW com.MyDTO(p.a, p.b, q.c, q.d)
FROM
(SELECT r.* FROM MyDTO1 r ) p
LEFT OUTER JOIN
(SELECT s.* FROM MyDTO2 s ) q
ON p.x = q.y 

or similar? (Above query has mixed with native and JPQL, so don't misunderstand)

I'm having a problem with this part I think.

FROM
(SELECT r.* FROM MyDTO1 r ) p

When I'm trying to execute I'm getting this error.

Exception Description: Syntax error parsing the query [.....], unexpected token [(]

Thank you!

Upvotes: 8

Views: 8260

Answers (2)

Mindaugas Jaraminas
Mindaugas Jaraminas

Reputation: 3447

Yes you can!

You have to use native queries. Here is an example:

emf = Persistence.createEntityManagerFactory("TEST")    
EntityManager em = emf.createEntityManager();
String queryString = "SELECT ID FROM ( SELECT * FROM ADDRESS WHERE ID < 0)";
Query query = em.createNativeQuery(queryString);
List<BigDecimal> result = query.getResultList();

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 692181

No, you can't. Quote from the documentation:

Note that HQL subqueries can occur only in the select or where clauses.

Upvotes: 5

Related Questions