2015-11-06 32 views
1

我有以下模式:如何處理多個JsonManagedReference和JsonBackReference?

model

這是我的代碼(我已刪除訪問者和無用屬性增加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在我的對象。

  1. 當我解析A,我想擺脫A_B小號B未經A_B小號越來越A
  2. 相反,當我解析B時,我想從A_B得到A,沒有得到BA_B s。

以我的實際代碼,所有A_B s元素總是null。當我刪除@JsonManagedReference("b")@JsonBackReference("b")時,(1)的結果是我需要的,但(2)的結果是無限遞歸

有人對我的問題有了解嗎?預先感謝幫助

回答

0

我無法找到一個最終的答案,但是這是最接近的解決方案

https://github.com/FasterXML/jackson-databind/issues/1091

添加此標籤每個類別的問題

@JsonIdentityInfo的(發電機= ObjectIdGenerators.PropertyGenerator.class,property =「id」) public class A {