|
Answer» Hibernate AGGREGATE functions are functions which CALCULATE the result of all the object property values which satisfy a given query condition or criteria. These functions are used in a HQL query which supports various functions like min(), max(), sum(), avg() and COUNT() in the SELECT statement. Assume that an entity named Student has been created which has been mapped to its corresponding table in the database. - To find the minimum age among all students, we can write a function as below:
@Test
public void whenMinAge_ThenReturnValue() {
int minAge = (int)session.createQuery("SELECT min(age) from Student")
.getSingleResult();
assertThat(minAge).ISEQUALTO(20);
} The getSingleResult() method returns an Object. Since we need an integer, the method has been downcast to int - To find the maximum age, we can write a function similar to the one we wrote for min()
@Test
public void whenMaxAge_ThenReturnValue() {
int maxAge = (int)session.createQuery("SELECT max(age) from Student")
.getSingleResult();
assertThat(minAge).isEqualTo(20);
} - To get the sum of all ages, we can use the sum() function
@Test
public void whenSumOfAllAges_ThenReturnValue(){
double sumOfAllAges = (double)session.createQuery("SELECT sum(age) from Student")
.getSingleResult();
assertThat(minAge).isEqualTo(20);
} Depending on the result, the method is downcast to either long or double - The avg() function is similar to sum. The avg() function always returns a double.
- The count() function is used to count the number of records. The count can also be based on a condition or criteria.
@Test
public void whenCountAll_ThenReturnValue() {
Long totalStudents = (Long) session.createQuery("SELECT count(*) from Student")
.getSingleResult();
assertThat(totalStudents).isEqualTo(5);
} The count() always returns a Long.
|