Jpql 从每组中选择一个最大行
我对 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果每个
entityId
的timestamp
是唯一的,您可以编写如下内容:If
timestamp
s are unique perentityId
, you can write something like this: