0

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?

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
User1230321
  • 1,435
  • 4
  • 23
  • 39

2 Answers2

0

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

Community
  • 1
  • 1
Yaroslav Stavnichiy
  • 20,738
  • 6
  • 52
  • 55
0

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
)
Joe Taras
  • 15,166
  • 7
  • 42
  • 55