I've created a simple @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. 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.
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).
The method where I call the query is listed below (I always get -1 as a result):
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
.
Note that if the source column is a Short
(equivalent), thenSUM(...)
widens the result to an Integer
in all cases. 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.
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).