在数据库返回树形结构数据之后,想转换成JSON返回页面时出错:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Infinite recursion (StackOverflowError) (through reference chain: com.myj.entity.Menu["parent"]->com.myj.entity.Menu["menus"]->......
无法写入内容:无限循环
解决办法:在关联关系属性的getter方法上分别加上@JsonManagedReference (一的一方)和 @JsonBackReference(多的一方)即可
@Entity
public class Menu {
private int id;
private String name;
private String address;
private Menu parent;
private int orderno;
private List<Menu> menus = new ArrayList<Menu>();
//加载主菜单时,把关联的子菜单也一并加载
@JsonManagedReference
@OneToMany(mappedBy="parent", fetch=FetchType.EAGER)
public List<Menu> getMenus() {
return menus;
}
public void setMenus(List<Menu> menus) {
this.menus = menus;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@JsonBackReference
@ManyToOne
@JoinColumn(name="parent_id")
public Menu getParent() {
return parent;
}
public void setParent(Menu parent) {
this.parent = parent;
}
public int getOrderno() {
return orderno;
}
public void setOrderno(int orderno) {
this.orderno = orderno;
}
}