【问题标题】:How to show data without ID in Spring如何在 Spring 中显示没有 ID 的数据
【发布时间】:2021-10-24 11:55:16
【问题描述】:

我正在向用户显示一些数据:

{
"id": 3,
"name": "AB:11",
"description": "AB:11 is an Imperial Black Barley Wine brewed with ginger, black raspberries and chipotle peppers. A 12.8% rollercoaster of ginger zestiness and chipotle smokiness, all bound together with dark berry tartness and the decadent residual body of a Black Barley Wine.",
"method": {
    "id": 3,
    "mash_temp": [
        {
            "id": 6,
            "temp": {
                "value": 68,
                "unit": "celsius"
            }
        }
    ]
}

}

但是,我想在没有“方法”的情况下显示它我只需要显示“mesh_temp”字段中的内容,所以它会是这样的:

"id": 3,
"name": "AB:11",
"description": "AB:11 is an Imperial Black Barley Wine brewed with ginger, black raspberries and chipotle peppers. A 12.8% rollercoaster of ginger zestiness and chipotle smokiness, all bound together with dark berry tartness and the decadent residual body of a Black Barley Wine.",
"mash_temp": [
   {
       "temp": {
       "value": 68,
       "unit": "celsius"
        }
   }
  ]
}

另外,就像您在第一个示例中看到的那样,我不想显示 mesh_temp 的 id

这些是我的实体:

总结一下:我只想显示:id、name、description 和 mash_temp 字段(没有 id)。任何建议如何做到这一点?

【问题讨论】:

    标签: spring-boot hibernate rest


    【解决方案1】:

    最简单的方法是创建一个 DTO,用于在 API 的响应中使用您想要的属性。这实际上是一个建议的模式,正是因为与此类似的用例:当您的内部模型与您希望通过 API 提供的模型不同时。

    【讨论】:

    • 你可以在这里看到一个相关的例子:baeldung.com/…
    • 我尝试使用 DTO,但问题是因为我的 MashTemp 字段返回 null
    • 您需要将原始MashTemp 映射到您的DTO。
    【解决方案2】:

    就像我回答你的其他问题一样,我建议使用 Blaze-Persistence Entity-Views 的 DTO 方法:How to show data to user with DTO

    【讨论】:

      【解决方案3】:

      如下图创建一个Model类并设置必填字段

      public class MyData {
      private Long id;
      private String name;
      private String description;
      private List<MashTemp> mash_temp;
      

      }

      class MashTemp {
      private String temp;
      private Integer value;
      private String unit;
      

      }

      【讨论】:

        猜你喜欢
        • 2017-01-01
        • 2021-07-09
        • 1970-01-01
        • 2017-04-30
        • 1970-01-01
        • 1970-01-01
        • 2013-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多