在mapper中写以下sql:
/**
* 获取未读系统消息、邀请消息的分别多少条
* @param user_id
* @return
* */
@Select("SELECT " +
"SUM(CASE WHEN info_status = 0 AND info_type = 0 THEN 1 ELSE 0 END) AS unread_system_num, " +
"SUM(CASE WHEN info_status = 0 AND info_type = 1 THEN 1 ELSE 0 END) AS unread_invite_num " +
"FROM user_information " +
"WHERE user_id = #{user_id}")
Map getUnReadInfosNum(@Param(value = "user_id") long user_id);
使用分段函数统计数量,返回值为Map集合,在controller中取对应key的value,报异常
java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Integer
发现mysql中通过分段统计返回值是BigDecimal,如果不处理返回的map集合,返回响应的是String类型
{
"data": {
"unread_system_num": "12",
"unread_invite_num": "23"
},
"errcode": 0,
"msg": "请求成功"
}
解决方法:
在service方法中,将BigDecimal类型转换Integer类型
方法一:
Integer a = Integer.parseInt(unReadInformationNum.get("unread_system_num").toString());
方法二:
Integer a = ((BigDecimal) unReadInformationNum.get("unread_system_num")).intValue();
转化成Integer之后,响应结果:
{
"data": {
"unread_system_num": 12,
"unread_invite_num": 23
},
"errcode": 0,
"msg": "请求成功"
}