[英]ClassCastException when using HQL
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 我得到ClassCastException:无法将Long转换为Integer
Question: what should i do to retrieve the values returned by the HQL as Integer instead of Long ???? 问题:如何检索HQL返回的值为Integer而不是Long ????
If you don't know which it will be ( Integer
or Long
), you can cast to Number
and call intValue()
or longValue()
. 如果你不知道它将是什么( Integer
或Long
),你可以longValue()
为Number
并调用intValue()
或longValue()
。 This way an Integer
or a Long
will work. 这样一个Integer
或Long
就可以了。
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. 这样做的一个小缺点就是你最终将数字拆箱并重新装箱以放入地图。
I guess the second column in the result - ie count(*)
returns Long
. 我想结果中的第二列 - 即count(*)
返回Long
。 You can get its int value by ((Long) objectArray[1]).intValue()
你可以通过((Long) objectArray[1]).intValue()
得到它的int值((Long) objectArray[1]).intValue()
Or (as suggested), better change your map to Map<Integer, Long>
, so that no information is eventually lost. 或者(如建议的那样),更好地将地图更改为Map<Integer, Long>
,以便最终不会丢失任何信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.