nullpointerexception after return entity from empty column

Viewed 94

I'm working on app in Spring Boot. I want to get object from data base but first time that object is empty. I did that because i want to restrict asking DB for only once per day. But when i return empy optiona(i try that solution but doesn't work) or null and provide if statement which should "catch" it, i got null pointer exception. Someone know how to resolve it ?

    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();
    }
2 Answers

You are calling statistics.getCreationDate() before null checking in if statatement. Probably that's why you are getting Nullpointerexception.

You can send statistics.getCreationDate() directly in todayWasNotSavedStatistics() method in if statement this way

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

I resolve this. There were two problems. Solutions is really simple, I have forgotten add no args contructor to Entity. Second was as Eklavya said calling statistics.getCreationDate() before checking null.

Related