Jpql 从每组中选择一个最大行

发布于 2024-10-04 00:30:31 字数 996 浏览 0 评论 0原文

我对 JPA 比较陌生,我想专门使用 jpql 解决以下问题(请注意,我使用的实现是 Datanucleus):我有一个版本化实体表,我想获取所有实体的最新版本在表中(即我有一个实体类,它有一个id(唯一标识一行、一个entityId(在整个版本中标识实体本身)和一个时间戳;我想获取所有entityId的最新版本实体)。我当前的代码如下:

    String innerQueryString = "SELECT entity.entityId, max(entity.timestamp) " +
                  "FROM Entity entity" +
                  "GROUP BY entity.entityId";

    Query getQuery = getEntityManager().createQuery(innerQueryString);

    List<Object[]> queryRes = getQuery.getResultList();
    List<IEntity> ret = new ArrayList<IEntity>();

    for (Object[] res : queryRes) { 
        ret.add(getEntity((Long)res[0], (Date)res[1]));
    }

    return ret;

getEntity 获取指定实体 ID 的实体数据,时间戳 我在这里找到了一些关于此代码如何在 sql 中工作的资源 http://www.xaprb.com/blog/2006/12/ 07/how-to-select-the-firstleastmax-row-per-group-in-sql/ 但我无法创建它的 jpql 版本,非常感谢您的帮助。

I am relatively new to JPA and I would like to solve the following problem using jpql exclusively (note that the implementation I am using is Datanucleus): I have a table of versioned entities, and I would like to get the latest version for all entities in the table (i.e. I have an entity class which has an id (which uniquely identifies a row, an entityId (which identifies the entity itself throughout versions) and a timestamp; I would like to get the latest version entity for all entityId). My current code goes as follows:

    String innerQueryString = "SELECT entity.entityId, max(entity.timestamp) " +
                  "FROM Entity entity" +
                  "GROUP BY entity.entityId";

    Query getQuery = getEntityManager().createQuery(innerQueryString);

    List<Object[]> queryRes = getQuery.getResultList();
    List<IEntity> ret = new ArrayList<IEntity>();

    for (Object[] res : queryRes) { 
        ret.add(getEntity((Long)res[0], (Date)res[1]));
    }

    return ret;

Where getEntity gets the entity data for the specified entityId, timestamp. I have found several resources on how this code would work in sql here http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/ but I cannot manage to create a jpql version of it. Help will be greatly appreciated, thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不忘初心 2024-10-11 00:30:31

如果每个 entityIdtimestamp 是唯一的,您可以编写如下内容:

SELECT e FROM Entity e
WHERE e.timestamp = (SELECT MAX(ee.timestamp) FROM Entity ee WHERE ee.entityId = e.entityId)

If timestamps are unique per entityId, you can write something like this:

SELECT e FROM Entity e
WHERE e.timestamp = (SELECT MAX(ee.timestamp) FROM Entity ee WHERE ee.entityId = e.entityId)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文