当我们根据类别进行统计,返回的数据类型为HashMap<String,Object>,获取数值类型,容易报java.math.BigDecimal cannot be cast to java.lang.Integer
场景如下:
// Mapper层
<select id="selectInfoByTest" resultType="map">
SELECT SUM(flag) as flags,taskid FROM qcdata GROUP BY taskid
</select>
// 接口
List<HashMap<String, Object>> selectInfoByTest();
// 调用代码
List<HashMap<String, Object>> result = qcDao.selectInfoByTest();
int flags=(Integer)result.get(0).get("flags"); // 报错
return JSONResult.ok(flags);
原因:sql中的 sum() 返回返回值在mybatis中是作为BigDecimal来返回的,而不能用Integer来接收
解决方式:
可以转换为字符串,然后再转换为int类型,在转换过程中,不能使用(String)这种方式强转,本不是String类型,可以使用toString(),也可以使用String.valueOf(),更简单的方式是用空字符串来转换;
public JSONResult test() {
List<HashMap<String, Object>> result = qcDao.selectInfoByTest();
// toString
int flags=Integer.parseInt(result.get(0).get("flags").toString());
// String.valueOf
int flags2=Integer.parseInt(String.valueOf(result.get(0).get("flags")));
// 空字符串
int flags3=Integer.parseInt(result.get(0).get("flags")+"");
return JSONResult.ok(flags+flags2+flags3);
}
需要注意的是,在强转之前最好判断一下是否为空,空字符串,类型是否匹配,避免强转失败;