【问题标题】:Select latest record for each id spring jpa选择每个id spring jpa的最新记录
【发布时间】:2020-06-21 18:04:28
【问题描述】:

我有一个这样的实体:

@Entity
class Point{
    @EmbeddedId
    private PointIdentity pointIdentity;
    private float latitude;
    private float longitude;

    @Embeddable
    public static class PointIdentity implements Serializable {
        private Long id;
        private ZonedDateTime timestamp;
    }
}

有EmbeddedId,所以“id”列可以是多条id相同的记录。

我需要使用我认为的 CriteriaQuery 和 JPA 规范获取每个 id 的最新记录,但不知道如何。

在 SQL 中,这将是这样的:

SELECT id, MAX(timestamp) 
FROM geodata 
GROUP BY id

有什么办法吗?

任何帮助,谢谢。

【问题讨论】:

  • 您提到有一个 id,但您没有告诉我们其中有哪些字段。
  • 每个id只有一个时间戳(在同一行)。目前尚不清楚您的组是什么(每个 id 的最后一条记录是什么意思)
  • @Lesiak 我的意思是每个 id 的最新记录
  • Id,根据定义,是唯一的。您不能有多个具有相同 id 的记录。
  • @Lesiak,有约束键,对不起,id+timestamp,更新了代码。所以这里可以是具有相同id的多行。也许 SQL 查询会让我的问题清楚。我需要这样做,只使用 spring jpa: SELECT id, MAX(timestamp) FROM geodata GROUP BY id

标签: spring spring-boot jpa spring-data-jpa criteria-api


【解决方案1】:

您可以轻松编写 JPQL 查询:

TypedQuery<Object[]> query = entityManager.createQuery(
    "select p.pointIdentity.id, max(p.pointIdentity.timestamp) from Point p group by p.pointIdentity.id",
    Object[].class);
List<Object[]> results = query.getResultList();

翻译为:

select
    point0_.id as col_0_0_,
    max(point0_.timestamp) as col_1_0_ 
from
    point point0_ 
group by
    point0_.id

或者,您可以使用条件查询:

CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
Root<Point> point = query.from(Point.class);
query.groupBy(point.get("pointIdentity").get("id"));
query.multiselect(
        point.get("pointIdentity").get("id"),
        criteriaBuilder.max(point.get("pointIdentity").get("timestamp"))
);
TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
List<Object[]> results = typedQuery.getResultList();

产生相同的 SQL。

【讨论】:

    猜你喜欢
    • 2020-05-29
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2021-01-23
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多