Bryan
Bryan

Reputation: 697

How to create a JPA query with LEFT OUTER JOIN

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?

Upvotes: 38

Views: 178163

Answers (4)

Smart Coder
Smart Coder

Reputation: 1738

Please see :

public interface YourDBRepository extends JpaRepository<Employee, Long> {

@Query("select new com.mypackage.myDTO(dep.empCode, dep.empName, em.EmployeeCode, em.EmployeeName) \n" +
        "from Department dep\n" +
        "left join  Employee em\n" +
        "on dep.DepartmentCode = em.DepartmentCode")  // this is JPQL so use classnames
List<myDTO> getDeptEmployeeList();

}

You can also use CrudRepository and include @JoinColumn with FK table class in PK table class and have List return list and then do find operation to achieve the same.

In Department entity class:

 @OneToMany
@Fetch(FetchMode.JOIN)
@JoinColumn(name="DEPT_CODE")
private List<Employee> employees;

CriteriaBuilder is yet another option.

Upvotes: 2

Xavier Dury
Xavier Dury

Reputation: 1571

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

Upvotes: 22

James
James

Reputation: 18379

Normally the ON clause comes from the mapping's join columns, but the JPA 2.1 draft allows for additional conditions in a new ON clause.

See,

http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/JPQL#ON

Upvotes: 7

Sai Ye Yan Naing Aye
Sai Ye Yan Naing Aye

Reputation: 6738

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.

Upvotes: 53

Related Questions