简体   繁体   English

如何使用 LEFT OUTER JOIN 创建 JPA 查询

[英]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:我开始学习 JPA,并基于我在 SQL 服务器中测试的以下原生 SQL 实现了一个带有 JPA 查询的示例:

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:从上面的 SQL 我构建了以下 JPQL 查询:

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.如您所见,我仍然缺少原始查询中的条件OR s.ClassID = f.Class2 My question is, how can I put it into my JPQL?我的问题是,如何将它放入我的 JPQL 中?

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. 因为您的Student实体与ClassTbl实体具有一对多关系。

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: 如果你有实体A和B没有任何关系,并且每个A严格为0或1 B,你可以这样做:

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. 这将为单个结果提供Object [] {a,b}或为多个结果提供List <Object [] {a,b}>。

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. 通常,ON子句来自映射的连接列,但JPA 2.1草案允许新的ON子句中的附加条件。

See, 看到,

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

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.您还可以使用 CrudRepository 并在 PK 表 class 中包含带有 FK 表 class 的 @JoinColumn 并让 List 返回列表,然后执行查找操作以实现相同的目的。

In Department entity class:在部门实体class:

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

CriteriaBuilder is yet another option. CriteriaBuilder 是另一种选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM