Spring boot 空列返回实体后的nullpointerexception

Spring boot 空列返回实体后的nullpointerexception,spring-boot,api,rest,spring-data-jpa,spring-data,Spring Boot,Api,Rest,Spring Data Jpa,Spring Data,我正在用SpringBoot开发应用程序。我想从数据库中获取对象,但第一次该对象是空的。我这样做是因为我想限制每天只向DB询问一次。但当我返回empyoptiona(我尝试了那个解决方案,但不起作用)或null并提供应该“捕获”它的if语句时,我得到了null指针异常。有人知道怎么解决吗 public Statistics createSaveAndReturnStatistics(){ 用户loggedUser=authService.getLoggedUser(); Statistics S

我正在用SpringBoot开发应用程序。我想从数据库中获取对象,但第一次该对象是空的。我这样做是因为我想限制每天只向DB询问一次。但当我返回empyoptiona(我尝试了那个解决方案,但不起作用)或null并提供应该“捕获”它的if语句时,我得到了null指针异常。有人知道怎么解决吗

public Statistics createSaveAndReturnStatistics(){
用户loggedUser=authService.getLoggedUser();
Statistics Statistics=statisticsRepository.findFirstBySeridOrderByIDdesc(loggedUser.getId());
ZonedDateTime creationDate=统计信息。getCreationDate();
if(statistics==null | | Today未保存统计信息(creationDate)){
//一些代码
返回statisticsRepository.save(newstatistics());
}
返回统计;
}
私有布尔值Today未保存统计学(ZonedDateTime creationDate){
ZonedDateTime now=ZonedDateTime.now(ZoneId.of(“UTC”));
返回creationDate.getDayOfYear()!=now.getDayOfYear()&&

creationDate.getDayOfYear()您正在调用
statistics.getCreationDate()
,然后将if statement签入为null。 可能这就是为什么会出现Nullpointerexception

您可以通过这种方式在if语句中直接在
todayWasNotSavedStatistics()
方法中发送
statistics.getCreationDate()

if (statistics == null || todayWasNotSavedStatistics(statistics.getCreationDate())) {
    //SOME CODE 
   return statisticsRepository.save(new Statistics());
}

我解决了这个问题。有两个问题。解决方案非常简单,我忘记了在实体中添加任何args构造函数。第二个问题是Eklavya在检查null之前调用statistics.getCreationDate()