Java 使用关系'反序列化JPA关系;杰克逊的身份证
我有两个JPA注释类,它们在数据库中有关系。我正在使用Jersey公开RESTAPIJava 使用关系'反序列化JPA关系;杰克逊的身份证,java,json,hibernate,jpa,jackson,Java,Json,Hibernate,Jpa,Jackson,我有两个JPA注释类,它们在数据库中有关系。我正在使用Jersey公开RESTAPI //package and imports @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @Entity public class Parent { @Id @GeneratedValue private Long id; privat
//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
我得到了以下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
。当我在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
请求中将整个父对象作为json来添加子对象,只想使用父id。有什么想法吗?我最终通过使用EntityManager的合并方法而不是持久化来解决它。然后将所有数据发送回客户端