hibernate 的sum(filed)引发的NullPointException错误解决过程

背景:

在用hql语句进行sum查询时遭遇NPE问题:

StringBuilder builder = new StringBuilder("select SUM(actualWorkingHour) from KqAttendanceDay where 1=1 ");
// 实际工时统计
Double timeCount = (double) dao.findOne(builder.toString(), list2);

if (timeCount == null){ timeCount = 0D;}

typeCount.setTimeCount(timeCount);

 因为查询时sum(filed)为null,所以导致NPE问题。

首先想到了改hql,原生sql解决方案如下

SELECT IFNULL(SUM(actual_working_hour),0) FROM kq_attendance_day

但这段sql转为hql时出现问题,导致无法执行。

再度分析,可能是null不能进行类型转换导致的报错,所以代码更改为:

StringBuilder builder = new StringBuilder("select SUM(actualWorkingHour) from KqAttendanceDay where 1=1 ");
// 实际工时统计
Object object = dao.findOne(builder.toString(), list2);

if (object == null){ object = 0D;}
Double timeCount = (double)object; 
typeCount.setTimeCount(timeCount);

这里采用代码逻辑进行一个转换。问题解决。

同时想起阿里的规范,记录下来:

原文地址:https://www.cnblogs.com/limingxian537423/p/8391971.html