Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a JPA query with LEFT OUTER JOIN

Tags:

java

jpa

jpql

I am starting to learn JPA, and have implemented an example with JPA query, based on the following native SQL that I tested in SQL Server:

SELECT f.StudentID, f.Name, f.Age, f.Class1, f.Class2  FROM Student f      LEFT OUTER JOIN ClassTbl s ON s.ClassID = f.Class1 OR s.ClassID = f.Class2 WHERE s.ClassName = 'abc' 

From the above SQL I have constructed the following JPQL query:

SELECT f FROM Student f LEFT JOIN f.Class1 s; 

As you can see, I still lack the condition OR s.ClassID = f.Class2 from my original query. My question is, how can I put it into my JPQL?

like image 539
Bryan Avatar asked Apr 18 '12 03:04

Bryan


People also ask

What is the correct query for left outer join?

SQL left outer join is also known as SQL left join. Suppose, we want to join two tables: A and B. SQL left outer join returns all rows in the left table (A) and all the matching rows found in the right table (B). It means the result of the SQL left join always contains the rows in the left table.

How do I join two entities in JPA?

The only way to join two unrelated entities with JPA 2.1 and Hibernate versions older than 5.1, is to create a cross join and reduce the cartesian product in the WHERE statement. This is harder to read and does not support outer joins. Hibernate 5.1 introduced explicit joins on unrelated entities.


1 Answers

Write this;

 SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc' 

Because your Student entity has One To Many relationship with ClassTbl entity.

like image 88
Sai Ye Yan Naing Aye Avatar answered Sep 19 '22 20:09

Sai Ye Yan Naing Aye