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