1

I have an entity that represents a change event for a specific object. Something like:

@Entity
public class Event {
    @Id
    private String eventId;
    private String objectId;
    private Instant creationDate;
    // other fields, getters, setters
}

There might be several event objects for a specific objectId.

Now I need to query all latest events for a each objectId (those that have max creationDate groping by objectId) .

If it was pure SQL I would write the following query:

SELECT event.*
FROM
  event event
  JOIN (
         SELECT
           e.object_id          object_id,
           MAX(e.creation_date) last_date
         FROM event e
         GROUP BY e.object_id
       ) latest_event
    ON latest_event.object_id = event.object_id
       AND event.creation_date = latest_event.last_date

But the similar join unfortunately doesn't work in JPA query.

Question: How to join a subquery in a JPA query?

Using a native query is not an option in my case, because I use Spring Data JPA repository with pagination functionality which doesn't work for native queries.

Sasha Shpota
  • 7,441
  • 6
  • 49
  • 100

2 Answers2

3
@Query( 
    value = "SELECT e FROM Event e " + 
            "WHERE e.creationDate = " +
            "(SELECT max(e2.creationDate) FROM Event e2 " + 
            "WHERE e2.objectId = e.objectId)"
)
Morteza Jalambadani
  • 1,881
  • 5
  • 19
  • 30
-1
SELECT *
FROM  Event
NATURAL JOIN
    (SELECT object_id, MAX(creation_date) AS creation_date
    FROM Event
    GROUP BY object_id) groupedEvent

if two equal max creation_date be in the same object_id

SELECT ev.*
FROM Event ev
INNER JOIN 
      (SELECT max(id) AS id
       FROM Event e
       INNER JOIN 
              (SELECT object_id, MAX(creation_date) AS last_date
               FROM Event GROUP BY object_id
              ) groupedEvent 
       ON e.object_id = groupedEvent.object_id
       AND e.creation_date = groupedEvent.last_date
       GROUP BY e.object_id) dist 
ON ev.id = dist.id;

```

onedaywhen
  • 50,748
  • 12
  • 91
  • 132
yang_song
  • 24
  • 3