【问题标题】:JDBC template throws NullPointerException when no rows found找不到行时,JDBC 模板抛出 NullPointerException
【发布时间】:2016-11-24 10:24:51
【问题描述】:

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

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]*

【问题讨论】:

  • 第 59 行是 jdbcTemplate.queryForObject ?

标签: spring jdbctemplate


【解决方案1】:

将您的选择语句更改为

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

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

【讨论】:

  • 我认为由于queryForObject 返回一个Object(可以为空),那么您的查询语句找不到任何要总结的行,所以它返回0 而不是@987654325 @。这对于对象 (Integer) 是完全合乎逻辑的,但对于原始类型 (int) 则不然。如果您将初始代码更改为Integer numberOfDays = jdbcTemplate.queryForObject ("select sum(number_of_days) from business_trip where name = ? and surname = ? and type = ?",new Object[]{name,surname,"UE"},Integer.class);,您还会获得 NPE 吗?这就像尝试以下内容:int i = (Integer) null;
  • 我做了一些研究,发现执行任何类型的“数学”(在本例中为 SUM)的 sql 查询在遇到 NULL 值而不是数字值时会抛出 NLP。另外:用 Integer 替换 int 并没有改变任何东西。
猜你喜欢
  • 2012-08-02
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2019-05-31
相关资源
最近更新 更多