选择多个总和HQL

时间:2013-01-24 09:46:41

标签: hibernate jpa-2.0 hql hibernate-4.x

如果我运行下面的查询,我会得到一个无法转换为Long的对象列表

String queryString = "select sum(cat.varaible1), sum(cat.varaible2) from Enrollment as cat where cat.created >= :startDate and cat.created <= :endDate";

如果我删除sum(cat.varaible2),那么我会得到一个包含long值的列表。

String queryString = "select sum(cat.varaible1) from Cat as cat where cat.created >= :startDate and cat.created <= :endDate";

为什么会这样?请解释

1 个答案:

答案 0 :(得分:0)

基本上,JPA是如何使用投影查询的。

如果SELECT语句中有单个表达式,则结果列表将正确输入。您可以使用它,或者从一开始就使用TypedQuery

如果SELECT语句中有多个表达式,则结果将是Collection Object个数组。在您的情况下,每个数组将有两个元素,它们都是Long类型。

如果要检索正确的结果类型,可以定义一个专用类来组合结果并使用构造函数表达式:

select new com.example.SumSum(sum(cat.varaible1), sum(cat.varaible2)) from ...