如何在JPA中的两列上运行SUM等聚合函数并显示其结果? [英] How to run an aggregate function like SUM on two columns in JPA and display their results?

查看:651
本文介绍了如何在JPA中的两列上运行SUM等聚合函数并显示其结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JPA的新手。所以我的问题对于某些人来说应该是如此简单。

I am new to JPA. So my question should be so simple to some.

下面是SQL中的简单查询,我想将其转换为JPA。我已经有一个名为 TimeEnt 的实体类。

Below is the Simple Query in SQL which i would like to convert to JPA. I already have an entity class called TimeEnt.

SELECT 
     SUM(TimeEntryActualHours) as UnBilledHrs,
     SUM (TimeEntryAmount) as UnbilledAmount
FROM TimeEnt WHERE MatterID = 200


推荐答案

JPA查询语言支持SELECT子句中的聚合函数,如AVG,COUNT,MAX,MIN,SUM,并且支持多个 select_expressions 在SELECT子句中,在这种情况下,结果是 List 对象数组(对象[] )。根据JPA规范:

The JPA Query Language does support aggregates functions in the SELECT clause like AVG, COUNT, MAX, MIN, SUM and does support multiple select_expressions in the SELECT clause, in which case the result is a List of Object array (Object[]). From the JPA specification:


4.8.1 SELECT子句的结果类型



...

4.8.1 Result Type of the SELECT Clause

...

SELECT
子句的结果类型由 select_expressions 类型定义>
包含在其中。
SELECT子句中使用多个
select_expressions 时,查询
的结果类型为 Object [] ,此结果中的
元素以
顺序对应于SELECT子句

规范的顺序,并且类型为结果类型
每个 select_expressions

The result type of the SELECT clause is defined by the the result types of the select_expressions contained in it. When multiple select_expressions are used in the SELECT clause, the result of the query is of type Object[], and the elements in this result correspond in order to the order of their specification in the SELECT clause and in type to the result types of each of the select_expressions.

换句话说,那种您在评论中提到的查询(因为您没有提供您的实体,我将根据您的示例提供答案)是支持的,没问题。这是一个代码示例:

In other words, the kind of query you mentioned in a comment (and since you didn't provide your entity, I'll base my answer on your example) is supported, no problem. Here is a code sample:

String qlString = "SELECT AVG(x.price), SUM(x.stocks) FROM Magazine x WHERE ...";
Query q = em.createQuery(qlString);
Object[] results = (Object[]) q.getSingleResult();

for (Object object : results) {
    System.out.println(object);
}



参考文献




  • JPA 1.0规格


    • 4.8.1 SELECT子句的结果类型

    • 4.8。 SELECT子句中的4个聚合函数

    • 这篇关于如何在JPA中的两列上运行SUM等聚合函数并显示其结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆