maaartinus
maaartinus

Reputation: 46382

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?

Upvotes: 3

Views: 2732

Answers (2)

Renato Barros
Renato Barros

Reputation: 177

You can use a sqlRestriction how workaround, something like:

Restrictions.sqlRestriction("1=1 group by this_.id, this_.size HAVING this_.size <> count(i_.id));

Here is a example:

ct.setProjection(Projections.sqlProjection(
                    "cobr_.client_id as clientID"
                    , new String[] {"clientID" }
                    , new Type[] { new LongType()}));
ct.add(Restrictions.sqlRestriction("1=1 group by cobr_.vlr_total,clientID having (sum(this_.vlr_net)-cobr_.vlr_total) < -20"));

Upvotes: 1

Dragan Bozanovic
Dragan Bozanovic

Reputation: 23552

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.

Upvotes: 3

Related Questions