我想编写一个方法,返回按字段’serviceId’分组的最后添加的对象列表.
以下HQL有效,但我想使用Criteria API编写它:
FROM Notification WHERE date IN
(SELECT MAX(date) FROM Notification GROUP BY serviceId)
ORDER BY date ASC
像这样的东西:
Criteria crit = session.createCriteria(Notification.class);
crit.add(Restrictions.in("date",
提前致谢.
编辑:
现在我需要一个类似的查询,使用eclipselink API = /
基本上,我需要最后N行(最大日期),其状态是下面描述的五个之一,按serviceId列分组.
由于我的经验不足,这是我能做到的最好的:
ExpressionBuilder builder = new ExpressionBuilder();
Expression exStatus1 = builder.get("status").equal(MessageType.START.toString());
Expression exStatus2 = builder.get("status").equal(MessageType.RUNNING.toString());
Expression exStatus3 = builder.get("status").equal(MessageType.PAUSED.toString());
Expression exStatus4 = builder.get("status").equal(MessageType.END_ERROR.toString());
Expression exStatus5 = builder.get("status").equal(MessageType.END_SUCCESS.toString());
ReadAllQuery query = new ReadAllQuery();
query.setReferenceClass(Notification.class);
query.setSelectionCriteria(((exStatus1).or(exStatus2).or(exStatus3).or(exStatus4).or(exStatus5)));
query.setMaxRows(listSize);
query.addDescendingOrdering("date");
避免结果行中重复serviceIds的子句…
最佳答案
您将要使用带有分离子查询的Criteria projection API:
原文链接:https://www.f2er.com/java/438035.htmlCriteria crit = session.createCriteria(Notification.class,"main");
DetachedCriteria notificationSubQuery = DetachedCriteria.forClass(Notification.class,"sub");
notificationSubQuery.setProjection(Projections.max("date"));
notificationSubQuery.add(Restrictions.eqProperty("sub.serviceId","main.serviceId"));
crit.add(Subqueries.propertyIn("date",notificationSubQuery));
crit.addOrder(Order.desc("date"));
这反映了您在HQL查询中使用的技术.
编辑:
我更新了查询以匹配主通知类和子查询之间的serviceId,基本上与此HQL查询相同:
FROM Notification main WHERE date IN
(SELECT MAX(sub.date) FROM Notification sub WHERE sub.serviceId = main.serviceId)
ORDER BY date ASC
这可以防止您在两个不同的serviceId之间匹配非最大日期的情况,如下所示:
serviceId = 1: date = 3,4,5
serviceId = 2: date = 4,5,6
旧查询返回:
serviceId: 1,date: 5
serviceId: 2,date: 5,6
新查询返回:
serviceId: 1,date: 5
serviceId: 2,date: 6
如果这对您有用,请告诉我.