Home >Database >Mysql Tutorial >How to Perform Group By and Aggregate Functions Using Hibernate Criteria?
How to Group by and Aggregate with Hibernate Criteria Object
In Hibernate, the Criteria API provides a convenient way to construct database queries. You can use Criteria to perform a wide range of operations, including filtering, sorting, and grouping.
To implement a SQL query like the following using Hibernate Criteria:
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name <operator> value GROUP BY column_name
You can use the groupProperty() method and the aggregate functions provided by the Projections class. For example, to find the maximum and sum of a particular column for a given condition, you could write the following Criteria object:
List result = session.createCriteria(SomeTable.class) .add(Restrictions.ge("someColumn", xxxxx)) .setProjection(Projections.projectionList() .add(Projections.groupProperty("someColumn")) .add(Projections.max("someColumn")) .add(Projections.sum("someColumn")) ).list();
This Criteria object will produce SQL similar to the following:
SELECT some_column, MAX(some_column), SUM(some_column) FROM some_table WHERE some_column >= xxxxx GROUP BY some_column
You can use this approach to perform complex grouping and aggregation operations with Hibernate Criteria.
The above is the detailed content of How to Perform Group By and Aggregate Functions Using Hibernate Criteria?. For more information, please follow other related articles on the PHP Chinese website!