Spring引导JPA - JSON没有嵌套对象与OneToMany关系

Sma*_*ajl 9 java orm json hibernate spring-boot

我有一个项目,处理对象的一些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;
}
Run Code Online (Sandbox Code Playgroud)

在发出请求时,我必须在JSON中指定所有内容:

{
  "id": 0,
  "reservations": [
    {}
  ],
  "name": "string",
  "dateOfDeparture": "string",
  "distance": 0,
  "price": 0,
  "seats": 0,
  "from": {
    "id": 0,
    "name": "string"
  },
  "to": {
    "id": 0,
    "name": "string"
  }
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢的是,实际上是指定引用对象的id而不是它们的整体,如下所示:

{
  "id": 0,
  "reservations": [
    {}
  ],
  "name": "string",
  "dateOfDeparture": "string",
  "distance": 0,
  "price": 0,
  "seats": 0,
  "from": 1,
  "to": 2
}
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?有人能给我一些关于如何做到这一点的见解吗?我只是找到了如何做相反的教程(我已有的解决方案).

Vad*_*mVL 24

对的,这是可能的.

为此,您应该使用Jackson注释对您的实体模型:

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

您的序列化JSON将代替以下内容:

{
    "from": {
        "id": 3,
        "description": "New-York"
    } 
}
Run Code Online (Sandbox Code Playgroud)

像这样:

{
    "from": 3
}
Run Code Online (Sandbox Code Playgroud)

官方文档中所述:

@JsonIdentityReference - 可选注释,可用于自定义对其启用了"对象标识"的对象的引用的详细信息(请参阅JsonIdentityInfo)

alwaysAsId = true 用作标记来指示是否所有引用的值都被序列化为ids(true);

请注意,如果使用值'true',反序列化可能需要其他上下文信息,并且可能使用自定义ID解析器 - 默认处理可能不够.