首页 > 解决方案 > 从空列返回实体后出现空指针异常

问题描述

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

    public Statistics createSaveAndReturnStatistics() {
        User loggedUser = authService.getLoggedUser();
        Statistics statistics = statisticsRepository.findFirstByUserIdOrderByIdDesc(loggedUser.getId());
        ZonedDateTime creationDate = statistics.getCreationDate();

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

        }
        return statistics;
    }

    private boolean todayWasNotSavedStatistics(ZonedDateTime creationDate) {
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("UTC"));

        return creationDate.getDayOfYear() != now.getDayOfYear() &&
                creationDate.getDayOfYear() <= now.getDayOfYear();
    }

标签: spring-bootapirestspring-data-jpaspring-data

解决方案


statistics.getCreationDate()在 if 语句中检查 null 之前调用。可能这就是你得到 Nullpointerexception 的原因。

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

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

推荐阅读