1
我有以下模式:如何處理多個JsonManagedReference和JsonBackReference?
這是我的代碼(我已刪除訪問者和無用屬性增加lisibility):
答:
@Entity
@Table(name = "a", schema = "public")
public class A implements Serializable {
@Id
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.a", cascade = CascadeType.ALL)
@JsonManagedReference("a")
private Set<A_B> ABs = new HashSet<>();
}
B:
@Entity
@Table(name = "b", schema = "public")
public class B implements Serializable {
@Id
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.b", cascade = CascadeType.ALL)
@JsonManagedReference("b")
private Set<A_B> ABs = new HashSet<>();
}
A _B:
@Entity
@Table(name = "a_b", schema = "public")
@AssociationOverrides({
@AssociationOverride(name = "pk.a",
joinColumns = @JoinColumn(name = "a_id")),
@AssociationOverride(name = "pk.b",
joinColumns = @JoinColumn(name = "b_id"))
})
public class A_B implements Serializable {
@EmbeddedId
private A_BId pk = new A_BId();
@OneToOne
private B b;
}
A_BId:
@Embeddable
public class A_BId implements Serializable {
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference("a")
private A a;
@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference("b")
private B b;
}
我使用com.fasterxml.jackson.datatype:jackson-datatype-hibernate4
解析JSON在我的對象。
- 當我解析
A
,我想擺脫A_B
小號B
未經A_B
小號越來越A
。 - 相反,當我解析
B
時,我想從A_B
得到A
,沒有得到B
從A_B
s。
以我的實際代碼,所有A_B
s元素總是null
。當我刪除@JsonManagedReference("b")
和@JsonBackReference("b")
時,(1)的結果是我需要的,但(2)的結果是無限遞歸
有人對我的問題有了解嗎?預先感謝幫助