在双向hibernate映射中隐藏父引用

时间:2017-05-23 14:57:11

标签: spring hibernate java-ee jackson

我有一个弹簧休息后端,有两个实体,双向关系店(一对多,多对一)。为了克服嵌套的提取问题,@ JsonManagedReference / @ JsonBackReference已用于实体之间的perent / child关系。

这些人看起来像这样:

@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数组。

但是,由于使用了jsonbackreferance,子元素中没有父元素的引用。 怎么能解决这个问题?在获取孩子时我需要父参考

1 个答案:

答案 0 :(得分:1)

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

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

private Integer parentId;

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