Spring 数据 JPA 到深度和奇怪的映射
Spring Data JPA to deep and weird mapping
最近我正在尝试创建具有多对一和一对多的 CRUD。我遇到了奇怪的结果,我无法处理它。
这是来自 /teams 的 JSON,我得到的
[
{
"id": 3,
"name": "team1",
"footballers": [
{
"id": 12,
"name": "karol",
"age": 0,
"team": {
"id": 3,
"name": "team1",
"footballers": [
12,
{
"id": 13,
"name": "Pauluszka",
"age": 0,
"team": 3
}
]
}
},
13
]
}
]
而我想要实现的是
[
{
"id": 3,
"name": "team1",
"footballers": [
{
"id": 12,
"name": "karol",
"age": 0
},
{
"id": 13,
"name": "Pauluszka",
"age": 1
}
]
}
]
这是我的 Pojo 的
Footballer.java
...somecodehere
@ManyToOne
@JoinColumn(name="team_id")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class , property = "id")
private Team team;
...somecodehere
Team.java
...somecodehere
@OneToMany(mappedBy = "team")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
private List<Footballer> footballers;
...somecodehere
如果你能给我一些提示,我将不胜感激,我应该改变什么来实现我想要的。
使用@JsonManagedReference
和@JsonBackReference
这里有例子http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion
您可以使用 @JsonView
注释来指定要在选定视图中序列化的字段。这将允许您根据需要省略 team
属性 of player
。
最近我正在尝试创建具有多对一和一对多的 CRUD。我遇到了奇怪的结果,我无法处理它。
这是来自 /teams 的 JSON,我得到的
[
{
"id": 3,
"name": "team1",
"footballers": [
{
"id": 12,
"name": "karol",
"age": 0,
"team": {
"id": 3,
"name": "team1",
"footballers": [
12,
{
"id": 13,
"name": "Pauluszka",
"age": 0,
"team": 3
}
]
}
},
13
]
}
]
而我想要实现的是
[
{
"id": 3,
"name": "team1",
"footballers": [
{
"id": 12,
"name": "karol",
"age": 0
},
{
"id": 13,
"name": "Pauluszka",
"age": 1
}
]
}
]
这是我的 Pojo 的
Footballer.java
...somecodehere
@ManyToOne
@JoinColumn(name="team_id")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class , property = "id")
private Team team;
...somecodehere
Team.java
...somecodehere
@OneToMany(mappedBy = "team")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
private List<Footballer> footballers;
...somecodehere
如果你能给我一些提示,我将不胜感激,我应该改变什么来实现我想要的。
使用@JsonManagedReference
和@JsonBackReference
这里有例子http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion
您可以使用 @JsonView
注释来指定要在选定视图中序列化的字段。这将允许您根据需要省略 team
属性 of player
。