Search code examples
javahibernatehibernate-criteria

Hibernate Criteria with condition on count


I need the equivalent of

SELECT m.id, count(i.id)
FROM master m LEFT JOIN item i on m.id = i.master_id
GROUP BY m.id, m.size
HAVING m.size <> count(i.id);

in Hibernate Criteria. Thanks to this question, I know how to get the grouped result as a list of Object[]:

ProjectionList projList = Projections.projectionList();
projList.add(Projections.groupProperty("master"));
projList.add(Projections.count("id"));

session
.createCriteria(Item.class)
.join("master")
.setProjection(projList)
.addRestriction(???) // <- my HAVING clause
.list();

I have no clue how to add the HAVING clause. I guess, it's something like Restrictions.eqProperty, but how can I refer to the count?

Is there a way how to refer to the resulting tuple elements in the query?


Solution

  • Hibernate Criteria API does not support HAVING clauses. Since it is deprecated anyway in newer Hibernate versions, I suggest you move to JPA Criteria API, or use HQL/JPQL or more advanced wrappers like Querydsl JPA.