簡體   English   中英

Spring引導JPA - JSON沒有嵌套對象與OneToMany關系

[英]Spring boot JPA - JSON without nested object with OneToMany relation

我有一個項目處理對象的一些ORM映射(有一些@OneToMany關系等)。

我使用REST接口來處理這些對象,使用Spring JPA來管理它們。

這是我的一個POJO的示例:

@Entity
public class Flight {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;
  private String name;
  private String dateOfDeparture;
  private double distance;
  private double price;
  private int seats;

  @ManyToOne(fetch = FetchType.EAGER)
  private Destination fromDestination;

  @ManyToOne(fetch = FetchType.EAGER)
  private Destination toDestination;

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "flight")
  private List<Reservation> reservations;
}

在發出請求時,我必須在JSON中指定所有內容:

{
  "id": 0,
  "reservations": [
    {}
  ],
  "name": "string",
  "dateOfDeparture": "string",
  "distance": 0,
  "price": 0,
  "seats": 0,
  "from": {
    "id": 0,
    "name": "string"
  },
  "to": {
    "id": 0,
    "name": "string"
  }
}

我更喜歡的是,實際上是指定引用對象的id而不是它們的整個體,如下所示:

{
  "id": 0,
  "reservations": [
    {}
  ],
  "name": "string",
  "dateOfDeparture": "string",
  "distance": 0,
  "price": 0,
  "seats": 0,
  "from": 1,
  "to": 2
}

這甚至可能嗎? 有人能給我一些關於如何做到這一點的見解嗎? 我只是找到了如何做相反的教程(我已有的解決方案)。

對的,這是可能的。

為此,您應該使用Jackson注釋對您的實體模型:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
protected Location from;  

您的序列化JSON將代替以下內容:

{
    "from": {
        "id": 3,
        "description": "New-York"
    } 
}

像這樣:

{
    "from": 3
}

官方文檔中所述

@JsonIdentityReference - 可選注釋,可用於自定義對其啟用了“對象標識”的對象的引用的詳細信息(請參閱JsonIdentityInfo

alwaysAsId = true用作標記,指示是否將所有引用的值序列化為ids(true);

請注意 ,如果使用值'true',則反序列化可能需要其他上下文信息,並且可能使用自定義ID解析程序 - 默認處理可能不夠。

您只能使用@JsonIgnore注釋忽略您的JSON內容。 要隱藏在JSON中的字段,可以使用@JsonIgnore對其進行注釋。 您可以像這樣更改您的JSON:

{
    "id": 0,
    "reservations": [
        {}
    ],
    "name": "string",
    "dateOfDeparture": "string",
    "distance": 0,
    "price": 0,
    "seats": 0,
    "from": {
        "id": 0
    },
    "to": {
        "id": 0
    }
}

但你不能這樣:

{
    "id": 0,
    "reservations": [
        {}
    ],
    "name": "string",
    "dateOfDeparture": "string",
    "distance": 0,
    "price": 0,
    "seats": 0,
    "from": 0,
    "to": 1
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM