【发布时间】:2014-05-03 10:02:23
【问题描述】:
我有两个在数据库中有关系的 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
}
当我对 http://localhost/children 执行 GET 请求时,我得到以下 JSON:
[{
"id": 1,
"name": "child1",
"parent": {
"id": 1,
"name": "parent"
}
}, {
"id": 2,
"name": "child2",
"parent": {
"id": 1,
"name": "parent"
}
}]
这是使用 Jackson 将数据库序列化为 JSON 的模型。
当我向http://localhost/children 执行POST 请求以使用以下有效负载添加孩子时:
{
"name": "child3",
"parent": {
"id": 1
}
}
子对象被持久化在数据库中,但父名称具有null 值。当我在 http://localhost/children 上执行另一个 GET 时,我看到了这一点
[{
"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 方法,但这并不能解决问题。我不想将整个 Parent 对象作为 json 放在我的 POST 请求中以添加孩子,但只想使用 Parent id。有什么想法吗?
【问题讨论】:
标签: java json hibernate jpa jackson