【问题标题】:MIssing parent reference in a bidirectional hibernate mapping在双向休眠映射中丢失父引用
【发布时间】: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


    【解决方案1】:

    序列化为 JSON 时会导致无限循环。这就是我们不做双向 JSON 关系的全部原因。

    如果您只需要 ID,我会为子实体添加一个额外的列。

    private Integer parentId;
    
    @Column(name = "ParentID", insertable=false, updateable=false)
    public Integer getParentId() {
        return parentId;
    }    
    

    【讨论】:

      猜你喜欢
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      相关资源
      最近更新 更多