Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of group by rows in hibernate with criteria

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?

like image 383
Arya Avatar asked Jan 08 '15 16:01

Arya


1 Answers

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)
like image 161
Pusker György Avatar answered Oct 23 '22 06:10

Pusker György