0

當我有兩個班在一個雙向多對多的關係如下圖所示:失去孩子的數據在雙向關係使用jacksonMapper

Parent implements Serializable{ 

     @ManytoMany(//declaration for join table) 
     @JsonBackReference 
     @com.fasterxml.jackson.annotation.JsonIgnore 
     Set <Child> childSet; 

    } 
    Child implements Serializable{ 
    @ManytoMany(//declaration for join table) 
    @JsonManagedReference 
    @com.fasterxml.jackson.annotation.JsonIgnore 
    Set <Parent> parentSet; 
    // other getter and setters 
    } 

我讓我的DAO調用得到特定的父母。隨着父母的細節,我想要取得父母的孩子。事情是這樣的:

Hibernate.initialize(parent.getChildSet()); //this works perfectly 
// and I get the details of parent along with the children in my DAO call. 

但是當我做了以下我的業務服務,同時將數據返回到控制器的孩子從父JSON字符串省略。

jacksonMapper.writeValueAsString(parent); 

所以我刪除裏面父類的思維,傑克遜可能會明白,這些領域是不可忽視的,同時,如下圖所示寫入字符串子屬性@JsonIgnore。但它仍然會忽略它們! :(

Parent implements Serializable{ 

    @ManytoMany(//declaration for join table) 
    @JsonBackReference 
    //@com.fasterxml.jackson.annotation.JsonIgnore 
    Set <Child> childSet; 

} 

任何想法,我可能會去錯了嗎?

+0

你可以添加你的數據庫查詢嗎? – k1133

+0

@ k1133數據庫端我使用休眠,它是一個選擇FoodItem上的所有查詢。我想要的類別也與foodItem一起來。但在使用jacksonMapper時,這些類別在返回的json字符串中被遺漏。 – dirai

+0

我已經刪除了Parent類中的Child屬性上的@JsonIgnore,他認爲Jackson可能會理解這些字段在寫入字符串時不會被忽略。但它仍然會忽略它們!:( – dirai

回答

0

我一直無法找出爲什麼發生這種情況。同時,我選擇了一個解決辦法。我正在給兩個單獨的呼叫DB。一個先取父,然後取第二個取基於讀取的parentId的孩子

或者,我可以在同一時間同時在服務中進行數據庫調用,並在發送之前將JSON準備爲複雜字符串到UI:

complex:{ 
parent:parent, 
child:child 
} 

無論哪種情況,這都是一種解決方法。理想的解決方案是僅在父類的映射中爲子類移除@ JsonIgnore。但不知何故,似乎並不奏效。如果我發現爲什麼「理想」解決方案無法正常工作,我會發布信息!

理想的解決方案已更新,答案在印度的2016年8月15日獨立日:

的問題是在映射:

Parent implements Serializable{ 

     @ManytoMany(//declaration for join table) 
     @JsonBackReference 
     @com.fasterxml.jackson.annotation.JsonIgnore 
     Set <Child> childSet; 

    } 

當你說@JsonBackReference這實際上意味着忽略此字段而寫Json,即說,

@JsonBackReference < - > @JsonIgnore

因此,當父項被序列化時,子項被省略。使用ORM映射,將註釋標註爲單側而不是雙側是最佳實踐。這樣,您可以在獲取數據時避免大量不必要的異常,其次,保持業務代碼的清潔。

JsonManagedReference vs JsonBackReference