java - 如果在 DB 中找不到数据,则返回空对象
问题描述
我想实现 Spring 端点以从 DB 获取数据。
@GetMapping("/notification/{id}")
public ResponseEntity<?> getNotificationByTransactionId(@PathVariable Integer id) {
return notificationService
.findByTransactionId(id)
.map(g -> NotificationNewDTO.builder()
.id(g.getId())
.status(g.getStatus())
.updated_at(g.getUpdated_at())
.build()
)
.map(ResponseEntity::ok)
.orElseGet(() -> notFound().build());
}
NotificationNewDTO
如果在数据库中找到注释,是否有某种方法可以只返回空对象?
解决方案
我将分两步处理:计算 DTO(检索或默认)并返回它。
它使事情更具可读性。
提取时提供默认值Optional<NotificationNewDTO>
,然后 ResponseEntity.ok()
在 dto 上调用:
NotificationNewDTO dto =
notificationService
.findByTransactionId(id)
.map(g -> NotificationNewDTO.builder() // Optional<NotificationNewDTO>
.id(g.getId())
.status(g.getStatus())
.updated_at(g.getUpdated_at())
.build()
)
.orElse(NotificationNewDTO.ofDefaultValue()); // change here
return ResponseEntity.ok(dto); // change here
让它在一个单一的流程中当然是可能的,但它不太清楚:
return
ResponseEntity.ok(
notificationService
.findByTransactionId(id)
.map(g -> NotificationNewDTO.builder()
.id(g.getId())
.status(g.getStatus())
.updated_at(g.getUpdated_at())
.build()
)
.orElse(NotificationNewDTO.ofDefaultValue())
)
推荐阅读
- python - 如何使用可观察的 RxPY 间隔定期调用异步协程?
- json - 我可以像在配置中为 sublime 做文件夹一样排除文件吗?
- c# - Monogame 程序不断随机丢弃大量帧
- java - 如何使用 HtmlUnit 驱动程序验证代理?
- mysql - 使用子查询时的 MySQL 分组
- r - “找不到对象'mtcars1'”:olsrr 函数中的错误
- datetime - Flutter DateTime , 打开关闭 if
- oracle-apex - 在两个 Oracle Apex 页面之间传输 blob
- sql-server - 如何计算每月的数量,然后在同一个选择语句中取平均值
- python - 如何有效地计算二维点的三个向量之间的全角(2pi)