Search code examples
javajpql

Sum operator and HashMap object as the result


I have created a JPQL like this: select sum(c.field1) field1, sum(c.field2) field2, sum(c.field3) field3 from class c

Now there are three problems: 1) I didn't find anywhere if I can use the synthax sum(c.field1) field1; 2) I didn't find anywhere if an aggregate query can have many fields; 3) when I try to execute this query the compiler return a Vector! The strangething is that I can't define the type of fields that will return because its are different (Long, Double and BigInteger) and If I try to return the values of the query it returns: [[Ljava.lang.Object;@f7b046]

this is the code:



         public Vector sumFilteredString(Class2 c2) {
            String query="select sum(c1.field1) field1, sum(c1.field2) field2, sum(c1.field3) field3, sum(c1.field4) field4, sum(c1.field5) field5 from Class1 c1 WHERE c1.idClass2=c2.id";

                Query q = getEntityManager().createQuery(query);

                return (Vector)q.getResultList();
    }

I try to use Vector because for me it's not important if I retrieve these values using HashMap.get("field name") or Vector.get(position) so if your solution consist to retrieve a Vector for me it is the same thing.


Solution

  • Look at the javadoc. The method getResultList() returns a List. you can't assume that the returned list is a Vector. And there's a a very good chance that it won't be a Vector since nobody uses Vector anymore since JDK 1.2.

    Your method should return a List, not a Vector.

    Each row of the returned List is an Object[]. That's defined by the JPA spec. And each cell element of the row is an object corresponding to the type of the field in your mapping. AFAIK, when you sum a field defined as a Long, you'll get a Long as result. If you sum a field defined as a BigDecimal, you'll get a BigDecimal.

    [[Ljava.lang.Object;@f7b046] is the result of calling toString() on the returned list. All it tells you is that the list contains a single object, whose toString() is [Ljava.lang.Object;@f7b046. This means that the object is an array of objects, and that the hashCode of the array is f7b046.