Hibernate Aggregate Functions – Hibernate 聚合函数

最后修改: 2019年 2月 14日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Hibernate aggregate functions calculate the final result using the property values of all objects satisfying the given query criteria.

Hibernate聚合函数使用满足给定查询条件的所有对象的属性值来计算最终结果。

Hibernate Query Language (HQL) supports various aggregate functions – min(), max(), sum(), avg(), and count() in the SELECT statement. Just like any other SQL keyword, usage of these functions is case-insensitive.

Hibernate查询语言(HQL)支持各种聚合函数 – min(), max(), sum(), avg(), and count()SELECT语句中。就像其他SQL关键字一样,这些函数的使用是不分大小写的。

In this quick tutorial, we’ll explore how to use them. Please note that in the examples below we use either the primitive or wrapper types to store the result of aggregate functions. HQL supports both, so it’s a matter of choosing which one to use.

在这个快速教程中,我们将探讨如何使用它们。请注意,在下面的例子中,我们使用原始类型或包装器类型来存储聚合函数的结果。HQL支持这两种类型,所以要选择使用哪一种。

2. Initial Setup

2.初始设置

Let’s start by defining a Student entity:

让我们从定义一个Student实体开始。

@Entity
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long studentId;

    private String name;

    private int age;

    // constructor, getters and setters
}

And populating our database with some students:

并为我们的数据库填充了一些学生。

public class AggregateFunctionsIntegrationTest {

    private static Session session;
    private static Transaction transaction;

    @BeforeClass
    public static final void setup() throws HibernateException, IOException {
        session = HibernateUtil.getSessionFactory()
          .openSession();
        transaction = session.beginTransaction();

        session.save(new Student("Jonas", 22, 12f));
        session.save(new Student("Sally", 20, 34f));
        session.save(new Student("Simon", 25, 45f));
        session.save(new Student("Raven", 21, 43f));
        session.save(new Student("Sam", 23, 33f));

    }

}

Note that our studentId field has been populated using the SEQUENCE generation strategy.

请注意,我们的studentId字段已经使用SEQUENCE生成策略进行了填充。

We can learn more about this in our tutorial on Hibernate Identifier Generation Strategies.

我们可以在Hibernate Identifier Generation Strategies的教程中了解更多信息。

3. min()

3.min()

Now, suppose we want to find the minimum age among all the students stored in our Student table. We can easily do it by using the min() function:

现在,假设我们想找到存储在Student表中的所有学生的最小年龄。我们可以通过使用min()函数轻松做到这一点。

@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 type. So, we have downcasted the output to an int.

getSingleResult()方法返回一个Object类型。因此,我们已经将输出降级为一个int

4. max()

4.max()

Similar to the min() function, we have a max() function:

min()函数类似,我们有一个max()函数。

@Test
public void whenMaxAge_ThenReturnValue() {
    int maxAge = (int) session.createQuery("SELECT max(age) from Student")
      .getSingleResult();
    assertThat(maxAge).isEqualTo(25);
}

Here again, the result is downcasted to an int type.

在这里,结果又被下移到一个int类型。

The min() and max() functions’ return type depends on the field in the context. For us, it’s returning an integer, as the Student’s age is an int type attribute.

min()max()函数的返回类型取决于上下文中的域。对我们来说,它返回的是一个整数,因为Student’s age是一个int类型属性。

5. sum()

5.sum()

We can use the sum() function to find the sum of all ages:

我们可以使用sum()函数来寻找所有年龄的总和。

@Test
public void whenSumOfAllAges_ThenReturnValue() {
    Long sumOfAllAges = (Long) session.createQuery("SELECT sum(age) from Student")
      .getSingleResult();
    assertThat(sumOfAllAges).isEqualTo(111);
}

Depending on the field’s data type, the sum() function returns either a Long or a Double.

根据字段的数据类型,sum()函数返回一个Long或一个Double

6. avg()

6.avg()

Similarly, we can use the avg() function to find the average age:

同样地,我们可以使用avg()函数来寻找平均年龄。

@Test
public void whenAverageAge_ThenReturnValue() {
    Double avgAge = (Double) session.createQuery("SELECT avg(age) from Student")
      .getSingleResult();
    assertThat(avgAge).isEqualTo(22.2);
}

The avg() function always returns a Double value.

avg()函数总是返回一个Double

7. count()

7.count()

As in the native SQL, HQL also provides a count() function. Let’s find the number of records in our Student table:

与本地SQL一样,HQL也提供一个count()函数。让我们找出我们的Student表中的记录数。

@Test
public void whenCountAll_ThenReturnValue() {
    Long totalStudents = (Long) session.createQuery("SELECT count(*) from Student")
      .getSingleResult();
    assertThat(totalStudents).isEqualTo(5);
}

The count() function returns a Long type.

count()函数返回一个Long类型。

We can use any of the available variations of the count() function – count(*), count(…), count(distinct …), or count(all …). Each one of them is semantically equivalent to its native SQL counterpart.

我们可以使用 count()函数的任何可用变体 – count(*), count(…), count(distinct …), 或者 count(all …)它们中的每一个都在语义上等同于其本地的SQL对应函数。

8. Conclusion

8.结语

In this tutorial, we briefly covered the types of aggregate functions available in Hibernate. Hibernate aggregate functions are similar to those available in plain-old SQL.

在本教程中,我们简要介绍了Hibernate中可用的聚合函数的类型。Hibernate的聚合函数与普通SQL中的函数类似。

As usual, the complete source code is available over on GitHub.

像往常一样,完整的源代码可以在GitHub上找到