話不多話,直接貼代碼。
@JsonIgnore
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="pid")
private Menu parent;
//@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true,fetch=FetchType.LAZY,mappedBy="parent")
@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL,mappedBy = "parent")
@OrderBy("position asc")
private List<Menu> children;
public Menu getParent() {
return parent;
}
public void setParent(Menu parent) {
this.parent = parent;
}
public List<Menu> getChildren() {
return children;
}
public void setChildren(List<Menu> children) {
this.children = children;
}
@Override
public String toString() {
return "Menu [id=" + id + ", parent=" + parent+ ", children=" + children+ ", name=" + name + ", uri=" + uri + ", style="
+ style + ", position=" + position + ", description="
+ description + ", enable=" + enable + "]";
}
報錯如下:
原因:內存溢出,從經驗來看肯定是哪裏出現了死循環了。
按照這個思路去分析,最終定位到 Menu對象中子Menu集合List<Menu> children ;
可這種自表關聯查詢的註解寫法都是正確的,菜單對象中父菜單id對應多個子菜單。
重點來了,請關注標紅的報錯位置:
在Menu類的toString方法裏面內存溢出,或者說死循環了。這就好理解了,因此children集合
裏面是Menu===>Menu裏面有children集合===>children集合裏面是Menu。。。。。。
一直死循環了。
解決:
將toString方法中children去掉
@Override
public String toString() {
return "Menu [id=" + id + ", parent=" + parent + ", name=" + name + ", uri=" + uri + ", style="
+ style + ", position=" + position + ", description="
+ description + ", enable=" + enable + "]";
}