【发布时间】:2017-05-23 14:57:11
【问题描述】:
我有一个 spring rest 后端,其中包含两个具有双向关系的实体(一对多、多对一)。为了克服嵌套提取问题,@JsonManagedReference/@JsonBackReference 已用于实体之间的父/子关系。
实体如下所示:
@Entity
@Table(name = "Parent")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Parent implements java.io.Serializable {
private Integer id;
private List<Child> childList;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
@JsonManagedReference
public List<Child> getChildList() {
return childList;
}
public void setChildListe(List<Child> childListe) {
this.childList = childList;
}
}
@Entity
@Table(name = "Child")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Child implements java.io.Serializable {
private Integer id;
private Parent parent;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ParentID")
@JsonBackReference
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
这在获取 Parent 元素时可以正常工作,然后将子集一起获取并显示为 json-array。
但是,由于使用了 jsonbackreference,子元素中没有对 parent 的引用。 如何解决这个问题?获取孩子时我需要父母参考
【问题讨论】:
标签: spring hibernate jakarta-ee jackson