简体   繁体   中英

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. The location table has following fields: id, employee_id(FK to employee table), latitude, longitude, created_date. This table contains many entries for an employee_id with different created_date. 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. 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.

Following query in MySQL does this:

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:

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!"

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?

otherwise see HQL left join of un-related entities

I think you can re-write your HQL query using EXISTS clause instead of LEFT JOIN as follow:

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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