You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot JPA Repository执行SUM求和出现空指针异常如何解决

根本原因

你遇到的空指针异常核心来自两个可能的触发点:

  • 当数据库ReportData对应表没有任何数据时,SUM()聚合函数的返回结果为NULL,你定义的totalTest()方法返回值是基本类型int,JPA尝试把NULL拆箱为int时就会抛出空指针异常
  • 你没有在Controller中正确注入reportRepository,未加@Autowired或者构造函数注入,导致repository实例本身为null,调用方法时触发空指针

修复方案

1. 修改Repository方法返回类型

将返回值从基本类型int改为包装类Integer,兼容SUM返回NULL的场景:

@Repository
public interface ReportRepository  extends JpaRepository<ReportData, Long>  {
  // 原生查询写法,注意原生SQL表名默认是实体类的下划线格式,表名如果是report_data就按下方写法,和实际表名保持一致即可
  @Query(value = "SELECT SUM(tests) FROM report_data", nativeQuery = true)
  Integer totalTest();
  
  // 也可以用JPQL写法,不需要加nativeQuery
  // @Query("SELECT SUM(m.tests) FROM ReportData m")
  // Integer totalTest();
}

2. 处理NULL默认返回0

如果需要没有数据时默认返回0,有两种处理方式:
第一种是在Controller调用处判断:

// 先确认已经注入repository
@Autowired
private ReportRepository reportRepository;

@GetMapping(value = "/reports")
public String statisticsPage (Model model){
   Integer total = reportRepository.totalTest();
   model.addAttribute("tests", total == null ? 0 : total);
   return "statistics";
}

第二种是直接在SQL层面用COALESCE函数处理NULL,不需要额外判断:

@Query(value = "SELECT COALESCE(SUM(tests), 0) FROM report_data", nativeQuery = true)
int totalTest();

3. 检查Repository注入

确保Controller层的reportRepository已经加了@Autowired注解,或者用构造函数注入,避免repository实例本身为null。

内容的提问来源于stack exchange,提问作者timmy tembo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 13:54:01