views:

122

answers:

2

Hi,

See the following mapping

public class SomeClass {

    private Integer someField;

}

When i call the following query

select someField, count(*) from SomeClass inner join OtherClass... group by ...

And i proccess the query as follows

Map<Integer, Integer> result = new HashMap<Integer, Integer>();

List<Object> objectList = query.list();
for(Object object: objectList) {
    Object [] objectArray = (Object []) object;

    result.put((Integer) objectArray[0], (Integer) objectArray[1]);
}

I get ClassCastException: can not convert Long to Integer

Question: what should i do to retrieve the values returned by the HQL as Integer instead of Long ????

+1  A: 

I guess the second column in the result - i.e. count(*) returns Long. You can get its int value by ((Long) objectArray[1]).intValue()

Or (as suggested), better change your map to Map<Integer, Long>, so that no information is eventually lost.

Bozho
Note that you may lose information. Rather just use `Long` instead of `Integer`.
BalusC
+1  A: 

If you don't know which it will be (Integer or Long), you can cast to Number and call intValue() or longValue(). This way an Integer or a Long will work.

result.put((Integer) objectArray[0], ((Number) objectArray[1]).intValue() );

The small downside with this is you end up unboxing the Number and reboxing it to put in the map.

karoberts