1

我在双向多对多关系中有两个类,如下所示:

  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 on Child 属性,认为杰克逊可能会理解在写入字符串时不会忽略这些字段,如下所示。但它仍然忽略它们!:(

 Parent implements Serializable{

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

}

知道我哪里可能出错了吗?

4

1 回答 1

1

我一直无法找出为什么会这样。同时,我选择了一种解决方法。我正在对 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 与 JsonBackReference

于 2016-04-29T03:47:47.083 回答