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.