简体   繁体   English

如何在Spring Data JPA中的HQL查询中编写左外部联接

[英]How to write left outer joins in HQL query in Spring Data JPA

I've a table called "location" where I'm capturing the latitude and longitude of my employees. 我有一个名为“ location”的表,用于捕获员工的经度和纬度。 The location table has following fields: id, employee_id(FK to employee table), latitude, longitude, created_date. 位置表具有以下字段:id,employee_id(从FK到employee表),纬度,经度,created_date。 This table contains many entries for an employee_id with different created_date. 该表包含具有不同created_date的employee_id的许多条目。 Now, from location table I want entries for all the employees with their latest created date. 现在,从位置表中,我需要所有雇员及其最新创建日期的条目。 That is the location table might contain two entries for employee_id 1 created on Jan 1st and Jan 2nd. 也就是说,位置表可能包含在1月1日和1月2日创建的employee_id 1的两个条目。 The resultant query should return me only the Jan 2nd entry for employee_id 1. Likewise I want entries from all the employees currently listed in location table. 结果查询应该只向我返回employee_id 1的1月2日条目。同样,我希望获得位置表中当前列出的所有雇员的条目。

Following query in MySQL does this: 在MySQL中执行以下查询:

SELECT loc1.* FROM location loc1 LEFT OUTER JOIN location loc2 
    ON (loc1.employee_id = loc2.employee_id AND 
        (loc2.createdDate > loc1.created_date AND loc2.id > loc1.id)) 
    where loc2.employee_id is null;

Now when I run the same as HQL query in Spring Data JPA the query becomes like this: 现在,当我在Spring Data JPA中运行与HQL查询相同的查询时,查询将如下所示:

SELECT loc1 FROM location loc1 LEFT OUTER JOIN location loc2 ON 
        (loc1.employee= loc2.employee AND 
               (loc2.createdDate > loc1.createdDate AND loc2.id > loc1.id)) 
        where loc2.employee is null

I get 我懂了

"Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join!" “由以下原因引起:org.hibernate.hql.internal.ast.QuerySyntaxException:预期要加入的路径!”

How can the path be given when the same table is used for join? 当同一表用于联接时,如何给出路径?

In case there is JPA relation has been defined between entities see How to perform left join in Hibernate Query Language? 如果在实体之间定义了JPA关系,请参见如何在Hibernate查询语言中执行左连接?

otherwise see HQL left join of un-related entities 否则,请参见HQL不相关实体的左联接

I think you can re-write your HQL query using EXISTS clause instead of LEFT JOIN as follow: 我认为您可以使用EXISTS子句而不是LEFT JOIN重新编写HQL查询,如下所示:

SELECT loc1 FROM location loc1
WHERE NOT EXISTS(
    SELECT 'NEXT'
    FROM location loc2
    WHERE loc2.employee = loc1.employee
    AND loc2.createdDate > loc1.createdDate AND loc2.id <> loc1.id
)

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

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