Spring boot中關於多對多查詢json無限遞歸問題

控制檯異常

#...
java.lang.Illegal State Exception: Cannot call sendError() after the response has been committed
#...

父類

BusinessTemplate.javajava

// ...
	@OneToMany(targetEntity = Link.class, mappedBy = "businessTemplate", fetch = FetchType.EAGER)
	private List<Link> links;
	// ...

子類

Link.javajson

//...
	@ManyToOne
	private BusinessTemplate businessTemplate;
	//...

問題描述

若是在LinkController中直接查詢Link對象會出現json無限遞歸問題。bash

@JsonIdentityInfo解決

分別在父子類中添加以下注釋: BusinessTemplate.javaapp

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class BusinessTemplate {
	//...
}

Link.javafetch

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Link {
	//...
}

json響應

{
    "id": 4,
    "name": "環節名稱",
    "businessTemplate": {
        "id": 2,
        "name": "預算業務",
        "type": "業務類型1",
        "links": [
            4
        ]
    },
    "nextLinkId": 0,
    "previousLinkId": 0
}
{
    "id": 2,
    "name": "預算業務",
    "type": "業務類型1",
    "links": [
        {
            "id": 4,
            "name": "環節名稱",
            "businessTemplate": 2,
            "nextLinkId": 0,
            "previousLinkId": 0
        }
    ]
}

參考

Jackson – Bidirectional Relationshipscode

相關文章
相關標籤/搜索