【问题标题】:Return empty object if data is not found into DB如果在 DB 中找不到数据,则返回空对象
【发布时间】:2019-11-28 08:50:59
【问题描述】:

我想实现 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());
    }

如果在 DB 中找到注释,有什么方法可以只返回空的 NotificationNewDTO 对象吗?

【问题讨论】:

  • 你不是已经在这里了吗.orElseGet(() -&gt; notFound().build()) ...?
  • 这会返回状态 404 而不是空对象。
  • return ResponseEntity.ok(notificationService.findByTransactionId(id).map(g -&gt; ...).orElse(NotificationNewDTO.builder().build()))
  • hm...我在地图前得到Syntax error on token ")", ElidedSemicolonAndRightBrace
  • 我的例子中的括号没有错。无论如何解决它应该是微不足道的......你没有字面上复制省略号,是吗?

标签: java spring rest spring-boot spring-data-jpa


【解决方案1】:

我会分两步处理:计算 DTO(已检索或默认)并返回它。
它使事情更具可读性。

当你提取Optional&lt;NotificationNewDTO&gt;然后在dto上调用ResponseEntity.ok()时给一个默认值:

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

【讨论】:

  • 什么是ofDefaultValue()
  • 一个公共静态方法,它将实例化您称之为空的NotificationNewDTO。您可以随意重命名。
  • 看起来我需要将它创建到 NotificationNewDTO 中?我得到The method ofDefaultValue() is undefined for the type NotificationNewDTO。你能给我样本应该是什么内容吗?
  • @Peter 只是创建新对象而不是 ofDefaultValue 老兄。它应该是直截了当的。你想要一个空的对象。只需在那里创建一个。
猜你喜欢
  • 2017-08-08
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-01
相关资源
最近更新 更多