Spring引导JPA – JSON没有嵌套对象与OneToMany关系
我有一个项目处理对象的一些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 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 }