Hibernate Group by Criteria Object

Bomberlatinos9 picture Bomberlatinos9 · Dec 13, 2011 · Viewed 112.7k times · Source

I would like to implement the following SQL query with Hibernate Criteria:

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name <operator> value
GROUP BY column_name

I have tried to implement this with Hibernate Criteria but it didn't work out.

Can anyone give me an example how this can be done with Hibernate Criteria? Thanks!

Answer

Ken Chan picture Ken Chan · Dec 13, 2011

Please refer to this for the example .The main point is to use the groupProperty() , and the related aggregate functions provided by the Projections class.

For example :

SELECT column_name, max(column_name) , min (column_name) , count(column_name)
FROM table_name
WHERE column_name > xxxxx
GROUP BY column_name

Its equivalent criteria object is :

List result = session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).list();