[英]Java EE Named Query with SUM() is not working
I've created a simple @NamedQuery: 我创建了一个简单的@NamedQuery:
@NamedQuery(name = "Etap.findSum", query = "SELECT e.czas FROM Etap e WHERE e.stan=1")
which is working fine. 工作正常。 The field
e.czas
was mapped as an Integer
and is of type INTEGER
in DB2 database. e.czas
字段已映射为Integer
并且在DB2数据库中的类型为INTEGER
。 Now when I am trying to change it in that way: 现在,当我尝试以这种方式进行更改时:
@NamedQuery(name = "Etap.findSum", query = "SELECT SUM(e.czas) FROM Etap e WHERE e.stan=1")
it fails, and what is more, the editor does not give a hint to choose the filed e.czas
as a parameter of the query. 它失败了,而且,编辑器也没有提示选择
e.czas
作为查询的参数。 When I change the type of the filed czas
to int
, the hint is given, but the query still doesn't work (it works when called from IBM Data Studio console). 当我将归档的
czas
的类型更改为int
,会给出提示,但是查询仍然不起作用(从IBM Data Studio控制台调用时,它可以工作)。
The method where I call the query is listed below (I always get -1 as a result): 下面列出了我调用查询的方法(结果始终为-1):
public Integer suma(){
try{
Query q = em.createNamedQuery("Etap.findSum");
Integer suma = (Integer)q.getSingleResult();
return suma;
}
catch(Exception e)
{
return -1;
}
What am I doing wrong in this case? 我在这种情况下做错了什么?
This is probably because the ORM is auto-widening the result in anticipation of the result turning into a Long
, and not an Integer
. 这可能是因为ORM在预期结果变为
Long
而不是Integer
会自动扩展结果。
Note that if the source column is a Short
(equivalent), then SUM(...)
widens the result to an Integer
in all cases . 请注意,如果源列是
Short
(等效),则SUM(...)
在所有情况下都将结果扩展为Integer
。 The documentation doesn't explicitly mention what happens in the case of an Integer
source column, but I'd imagine the db auto-widens it in the case the result is sufficiently large. 该文档没有明确提及在使用
Integer
源列的情况下会发生什么,但是我认为在结果足够大的情况下,数据库会自动扩展它。
The ORM then has to account for this potential behavior by making sure it can handle a long - so it casts it to that type, unless the result is specifically stated to be safe (by casting it to Integer
on the db). 然后,ORM必须通过确保可以处理long来考虑这种潜在的行为-因此将其强制转换为该类型,除非明确声明结果是安全的(将其强制转换为db上的
Integer
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.