问题描述
我有一个处理对象的一些ORM映射的项目(有一些 @OneToMany
关系等等。)
我使用REST接口来处理这些对象,并使用Spring JPA在API中管理它们。
这是我的一个POJO示例:
@Entity
public class Flight {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
私人长ID;
私人字符串名称;
private String dateOfDeparture;
私人双倍距离;
私人双重价格;
private int席位;
@ManyToOne(fetch = FetchType.EAGER)
private Destination fromDestination;
@ManyToOne(fetch = FetchType.EAGER)
私人Destination toDestination;
@OneToMany(fetch = FetchType.EAGER,mappedBy =flight)
private List< Reservation>保留;
}
提出请求时,我必须在JSON中指定所有内容:
{
id:0,
reservations:[
{}
$ bname:string,
dateOfDeparture:string,
距离:0,
price:0,
seat:0,
from:{
id:0,
name:string
},
to :{
id:0,
name:string
}
}
我更喜欢的是实际指定引用对象的id而不是它们的整体,如下所示:
<$ p
id:0,
reservations:[
{}
],
name:字符串,
dateOfDeparture:字符串,
距离:0,
价格:0,
席位:0,
从:1,
到:2
甚至可能吗?有人能给我一些关于如何做到这一点的见解吗?我只找到如何做相反的教程(我已经有了解决方案)。 是的,这是可能的。
为此,您应该将一对Jackson注释用于实体模型:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property =id)
@JsonIdentityReference(alwaysAsId = true)
protected from;
您的序列化JSON将会看起来不是这样:
{
from:{
id:3,
description:New-York
}
}
像这样:
{
from:3
}
正如:
$ b
I have a project which deals with some ORM mapping of objects (there are some @OneToMany
relations etc).
I am using REST interface to treat these objects and Spring JPA to manage them in the API.
This is an example of one of my POJOs:
@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;
}
When making a request, I have to specify everything in the JSON:
{
"id": 0,
"reservations": [
{}
],
"name": "string",
"dateOfDeparture": "string",
"distance": 0,
"price": 0,
"seats": 0,
"from": {
"id": 0,
"name": "string"
},
"to": {
"id": 0,
"name": "string"
}
}
What I would prefer, is actually specifying the id of referenced object instead of their whole bodies, like this:
{
"id": 0,
"reservations": [
{}
],
"name": "string",
"dateOfDeparture": "string",
"distance": 0,
"price": 0,
"seats": 0,
"from": 1,
"to": 2
}
Is that even possible? Could someone give me some insight on how to do this? I am only finding tutorials on how to do the opposite (the solution I already have).
Yes, it is possible.
For this purpose you should use pair of Jackson annotations to your entity model:
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
protected Location from;
Your serialized JSON will look instead of this:
{
"from": {
"id": 3,
"description": "New-York"
}
}
like this:
{
"from": 3
}
As mentioned in official documentation:
这篇关于Spring引导JPA - 没有带OneToMany关系的嵌套对象的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!