如果我运行下面的查询,我会得到一个无法转换为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";
为什么会这样?请解释
答案 0 :(得分:0)
基本上,JPA是如何使用投影查询的。
如果SELECT
语句中有单个表达式,则结果列表将正确输入。您可以使用它,或者从一开始就使用TypedQuery
。
如果SELECT
语句中有多个表达式,则结果将是Collection
Object
个数组。在您的情况下,每个数组将有两个元素,它们都是Long
类型。
如果要检索正确的结果类型,可以定义一个专用类来组合结果并使用构造函数表达式:
select new com.example.SumSum(sum(cat.varaible1), sum(cat.varaible2)) from ...