首页 > 解决方案 > 如果在 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如果在数据库中找到注释,是否有某种方法可以只返回空对象?

标签: javaspringrestspring-bootspring-data-jpa

解决方案


我将分两步处理:计算 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())
    )

推荐阅读