JPA查询:加入具有分组条件的子查询

时间:2018-08-17 08:23:10

标签: java sql spring-data-jpa hql jpql

我有一个实体,代表特定对象的变更事件。像这样:

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

一个特定的objectId可能有多个事件对象。

现在我需要查询每个objectId (那些最大creationDate摸索objectId的所有最新事件)。

如果是纯SQL,我将编写以下查询:

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

但是不幸的是,类似的联接在JPA查询中不起作用。

问题:如何在JPA查询中加入子查询?

在我的情况下,不能使用本机查询,因为我使用具有分页功能的Spring Data JPA存储库,该功能不适用于本机查询。

2 个答案:

答案 0 :(得分:2)

@Query( 
    value = "SELECT e FROM Event e " + 
            "WHERE e.creationDate = " +
            "(SELECT max(e2.creationDate) FROM Event e2 " + 
            "WHERE e2.objectId = e.objectId)"
)

答案 1 :(得分:0)

SELECT *
FROM  Event
NATURAL JOIN
    (SELECT object_id, MAX(creation_date) AS creation_date
    FROM Event
    GROUP BY object_id) groupedEvent

如果两个相等的最大creation_date在同一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;

```