SUM映射问题
当我们根据类别进行统计,返回的数据类型为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);
}
需要注意的是,在强转之前最好判断一下是否为空,空字符串,类型是否匹配,避免强转失败;
sum 返回映射问题(sum报表统计接口返回)
MyBatis sum 返回值映射
mapper.xml代码
<select id="pieChart" resultType="map">
select sum(com.thinkmoney*ord.commnumber) as totalPrice , com.category as category from commodity com,orders ord
where com.commid=ord.commid and ord.orderstatus=1
GROUP BY com.category
</select>
pojo
private static final long serialVersionUID = 1L;
private String id;
private String ordernumber;
private Date ordertime;
private String commname;
private String commid;
private String commdesc;
private Integer commnumber;
private BigDecimal price;
private String useraddress;
private Integer orderstatus;
private String username;
private String mobilephone;
private Integer kdstatus;
private String kdnumber;
private String buyuserid;
private String selluserid;
private Commodity commodity;
private BigDecimal totalPrice;
controller
@GetMapping("/echars/piechart")
public String piechart(HttpSession session,HttpServletRequest request){
List<HashMap<String,Object>> result =ordersService.pieChart();
List<String> totalPriceList= new ArrayList<String>();
List<String> categoryList= new ArrayList<String>();
for( Map<String, Object> mapList : result ) {
totalPriceList.add(mapList.get("totalPrice").toString());
categoryList.add(mapList.get("category").toString());
}
session = request.getSession();
System.out.println("totalPriceList:"+totalPriceList+",categoryList:"+categoryList);
session.setAttribute("totalPriceList",totalPriceList);
session.setAttribute("categoryList",categoryList);
return "/admin/echars/piechart";
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。