【发布时间】:2020-08-30 20:41:26
【问题描述】:
我正在使用 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-boot api rest spring-data-jpa spring-data