1. 程式人生 > >返回JSON出現Infinite recursion無限迴圈錯誤的解決

返回JSON出現Infinite recursion無限迴圈錯誤的解決

在資料庫返回樹形結構資料之後,想轉換成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;
	}
	
	
}