我有两个在数据库中有关系的JPA注释类。我使用Jersey来公开REST api。
//package and imports
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
public class Parent {
@Id
@GeneratedValue
private Long id;
private String name;
//Getters and setters
}
//package and imports
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
public class Child {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne
private Parent parent;
//Getters and setters
}
当我在GET
上执行http://localhost/children
请求时,我收到以下JSON:
[{
"id": 1,
"name": "child1",
"parent": {
"id": 1,
"name": "parent"
}
}, {
"id": 2,
"name": "child2",
"parent": {
"id": 1,
"name": "parent"
}
}]
这是使用Jackson将数据库序列化为JSON的模型。
当我向POST
执行http://localhost/children
请求以使用以下有效内容添加子项时:
{
"name": "child3",
"parent": {
"id": 1
}
}
子项持久存储在数据库中,但父项名称的值为null
。当我在GET
http://localhost/children
时,我看到了这一点
[{
"id": 1,
"name": "child1",
"parent": {
"id": 1,
"name": "parent"
}
}, {
"id": 2,
"name": "child2",
"parent": {
"id": 1,
"name": "parent"
}
}, {
"id": 3,
"name": "child3",
"parent": {
"id": 1
}
}]
我使用了@JsonIdentityInfo/@JsonIdentityReference
方法,但这并没有解决问题。我不想在我的POST
请求中将整个Parent对象作为json添加到子级但只想使用Parent id。有什么想法吗?
答案 0 :(得分:0)
我最终通过使用EntityManager的merge方法而不是persist来解决它。然后将所有数据发送回客户端。