代码之家  ›  专栏  ›  技术社区  ›  Tomasz Stępnik

空列返回实体后的nullpointerexception

  •  0
  • Tomasz Stępnik  · 技术社区  · 5 年前

        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();
        }
    
    0 回复  |  直到 5 年前
        1
  •  1
  •   Eklavya    5 年前

    statistics.getCreationDate() 在空签入if statement之前。 可能这就是为什么你会得到Nullpointerexception。

    你可以发送 统计.getCreationDate() 直接在 todayWasNotSavedStatistics() if语句中的方法

    if (statistics == null || todayWasNotSavedStatistics(statistics.getCreationDate())) {
        //SOME CODE 
       return statisticsRepository.save(new Statistics());
    }
    
        2
  •  0
  •   Tomasz Stępnik    5 年前