Gson 转换hibernate级联对象出现StackOverFlow(堆栈溢出)问题

< many-to-one>和< one-to-many>属性的对象级联关系在转换时会造成死循环,报stackOverFlowException。

比如下面这段:

@OneToMany(cascade=CascadeType.ALL,mappedBy="parent",fetch=FetchType.EAGER)
    public List<Menu> getChildren() {
        return children;
    }

    public void setChildren(List<Menu> children) {
        this.children = children;
    }

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="parent_id")
    public Menu getParent() {
        return parent;
    }

    public void setParent(Menu parent) {
        this.parent = parent;
    }

这是时候就去要忽略掉不需要生成的那个字段,两个都忽略或者忽略其中的一个都可以。在属性上加上 transient,如下在parent上加上了transient:

    //父节点(Menu)
    private transient Menu parent;

这样gson就能正确生成数据了。

原文地址:https://www.cnblogs.com/ShawnYang/p/6803758.html