JDBC 模板在找不到行时抛出 NullPointerException

JDBC template throws NullPointerException when no rows found

我有一个对单列数值求和的查询:

int numberOfDays = jdbcTemplate.queryForObject
("select sum(number_of_days) from business_trip where name = ? and surname = ? and type = ?",new Object[]{name,surname,"UE"},Integer.class);

只要所选用户有UE类别的出差就可以正常使用。然后它正确地总结旅行天数。但是,如果没有 UE 类别的行程,我得到的不是零,而是 NullPointerException。我可以将此行放在 try/catch 中,但这是一种解决方法。我想弄清楚为什么在这种情况下会抛出NPE。

*2016-11-24 11:13:02.613 ERROR 8316 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException: null
at com.tfb.dao.BusinessTripDAO.getKrajoweTripsDaysForEmployee(BusinessTripDAO.java:59) ~[classes/:na]*

将您的 select 语句更改为

"select coalesce(sum(number_of_days), 0) from business_trip where name = ? and surname = ? and type = ?"

这样,如果你得到null,它将被转换为0。