问题
当我们在sql中使用count方法,然后返回值数据用map接收的
Map<String, Object> rst = manageService.searchCnt();
int count1=(Integer)rst.get("count1");
int count2=(Integer)rst.get("count2");
int count = count1 + count2;
运行到int count1=rst.get("count1");时报错
ERROR 2019-11-26 15:54:09,171 java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
分析
为什么会是Long呢?
就算结果用Map<String, Integer>接收,在运行 count = count1 + count2;时,仍旧会报Long转Integer异常,为什么用Integer接收仍旧返回Long呢?
之后看了这个文章 https://www.oschina.net/question/1991476_181297?sort=time
当数据库字段为 int 型(有符号int型),但是如果在 sql 中使用了某些函数,jdbc 会自动转型为 long,这个行为是 jdbc 自动做的,目的是为了防止数据溢出
解决
解决的办法通常两个:
1:
预知可能的转型,使用正确的类型变量去接收值
,例如用 Long变量去接收 select sum(xxx)值。
2:使用
getNumber(attr).intValue() 确切一定得到 Integer 值
,或者
使用 getNumber(attr).longValue() 确切一定得到 Long 值。
修改后代码
Map<String, Long> rst= tbCourseActivityService.getEnrollCountByType();
int count1=rst.get("count1").intValue();
int count2=rst.get("count2").intValue();
int count = count1 + count2;
总结
使用正确的变量去接收返回值,这样才不会一脸茫然,针对返回值也能使用适当的方法,得到想要的结果。