I want to count the number of group by
rows with hibernate Criteria API, but i can only count number of rows aggregated in each group:
ProjectionList projectionList = Projections.projectionList()
.add(Projections.groupProperty("color"))
.add(Projections.rowCount());
Criteria criteria = session.createCriteria("ProductEntity");
criteria.setProjection(projectionList);
// adding some criteria
List results = criteria.list();
Above code will results in this query:
select p.color, count(*) from product p group by p.color
But i want this query:
select count(*) from (select p.color from product p group by p.color)
I know it's possible with HQL, but i don't want to use it. So how can i do this with Criteria API?
If you want to know how many different colors are present you should use
Projections.countDistinct("color")
This will result a query which will return the same result as this:
select count(*) from (select p.color from product p group by p.color)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With