Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL JOINS with nested SELECT

Tags:

jpql

openjpa

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!

like image 266
sura2k Avatar asked Apr 17 '12 05:04

sura2k


People also ask

How to join related entities in a JPQL query?

List<BookPublisherValue> bookPublisherValues = em.createQuery (“SELECT new org.thoughts.on.java.model.BookPublisherValue (b.title, b.publisher.name) FROM Book b”,BookPublisherValue.class).getResultList (); 2. Join related entities in the FROM clause You can, of course, also join related entities in JPQL queries.

What is a subselect query 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.

What is a JPQL from clause in hibernate?

Hibernate, or any other JPA implementation, maps the entities to the according database tables. The syntax of a JPQL FROM clause is similar to SQL but uses the entity model instead of table or column names. The following code snippet shows a simple JPQL query in which I select all Author entities.

How to do right joins in the where clause in JPA?

JPA doesn't provide right joins where we also collect non-matching records from the right entity. Although, we can simulate right joins by swapping entities in the FROM clause. 5. Joins in the WHERE Clause 5.1. With a Condition We can list two entities in the FROM clause and then specify the join condition in the WHERE clause.


Video Answer


2 Answers

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

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

like image 166
JB Nizet Avatar answered Oct 11 '22 23:10

JB Nizet


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();
like image 38
Mindaugas Jaraminas Avatar answered Oct 11 '22 22:10

Mindaugas Jaraminas