计数条件为

时间:2017-07-19 18:11:18

标签: java hibernate hibernate-criteria

我需要相当于

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

在Hibernate Criteria中。感谢this question,我知道如何将分组结果作为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();

我不知道如何添加HAVING子句。我猜,它类似Restrictions.eqProperty,但我怎么能参考计数呢?

有没有办法在查询中引用生成的元组元素?

2 个答案:

答案 0 :(得分:3)

Hibernate Criteria API不支持HAVING子句。由于在较新的Hibernate版本中它已被弃用,我建议您转到JPA Criteria API,或使用HQL / JPQL或更高级的包装器,如Querydsl JPA

答案 1 :(得分:1)

您可以使用sqlRestriction如何解决方法,例如:

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

这是一个例子:

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