开发者

Jpql selecting the one maximum row from each group

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开发者_StackOverflow appreciated, thanks.


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜