我使用嵌套实体向我的端点发送请求。但是当我用Parent解析请求体时,getChild总是返回null
。
我的实体:
@Entity
public class Parent {
@Id
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen")
@Type(type = "pg-uuid")
private UUID id;
@Column(nullable = false)
private String name;
@JsonBackReference(value="child")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(foreignKey = @ForeignKey(name = "child_id"))
private Child child;
public Parent() {
}
public Card(UUID id, String name, Child child) {
this.id = id;
this.name = name;
this.child = child;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setChild(Child child) {
this.child = child;
}
public Child getChild() {
return child;
}
}
@Entity
public class Child {
@Id
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen")
@Type(type = "pg-uuid")
private UUID id;
@Column(nullable = false)
private String name;
@JsonManagedReference(value="child")
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL)
private List<Parent> parents;
public Child() {
}
public Child(UUID id, String name, List<Parent> parents) {
this.id = id;
this.name = name;
this.parents = parents;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Parent> getParents() {
return parents;
}
public void setParents(List<Parent> parents) {
this.parents = parents;
}
}
我向/parents
发出POST请求以创建父级,但我有一个尚未创建的子级,但我想一起创建它们并链接它们。
我发送的请求:
{
"name": "Your name",
"child" : {
"name": "Child name"
}
}
我期待的是什么:
{
"id": "uuid",
"name": "Your name",
"child" : {
"id": "childuuid"
"name": "Child name"
}
}
但我得到的是:
{
"id": "uuid",
"name": "Your name"
}
我的控制器:
@RequestMapping(value = "/parents", method = RequestMethod.POST)
public Card createParent(
@RequestBody Parent parent
) {
Child child = parent.getChild(); // always null :(
....do something to create both child and parent
return parentService.create(parent);
}
答案 0 :(得分:0)
点击此帖:JsonManagedReference vs JsonBackReference
JsonBackReference阻止项被序列化,这是为了避免在序列化时无限递归。
Parent1 - &gt;孩子 - &gt; Child1 - &gt;父母 - &gt; Parent1 - &gt;孩子 - &gt; Child1
您可以反转JsonManagedReference,JsonBackReference关系,但在序列化Parent时将忽略parents字段。
我发现DTO运行良好,它们将您的传输格式和数据库格式分离,这非常有用。