Write HQL clause using Hibernate Criteria API

我与影子孤独终老i 提交于 2019-12-03 16:09:14

You're going to want to use the Criteria projections API with a detached subquery:

Criteria 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"));

This mirrors the technique you are using in your HQL query.

EDIT:

I updated the query to match serviceId between your main notification class and your sub query, essentially the same as this HQL Query:

FROM Notification main WHERE date IN 
    (SELECT MAX(sub.date) FROM Notification sub WHERE sub.serviceId = main.serviceId) 
ORDER BY date ASC

This prevents the case where you would have a non-maximum date matching between two different serviceIds like so:

serviceId = 1: date = 3,4,5
serviceId = 2: date = 4,5,6

Old query return:

serviceId: 1, date: 5
serviceId: 2, date: 5,6

New query return:

serviceId: 1, date: 5 
serviceId: 2, date: 6

Let me know if this works for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!