1. 程式人生 > >SpringData JPA框架使用時出現JSON迴圈依賴解決方案

SpringData JPA框架使用時出現JSON迴圈依賴解決方案

發現問題出在轉換JSON的環節,出現死迴圈,如下為解決方法

Book類上面放入

@JsonIgnoreProperties(ignoreUnknown = true, value = 
{"hibernateLazyInitializer", "handler", "fieldHandler"})
public class Book{
... ...

Book類中屬性上註解,此屬性Author中引用了private Set books;

public class Book{
... ...
@JsonIgnoreProperties(ignoreUnknown = true, value = {"books"})
private Set<Author> authors;
... ...

Author類上面放入

@JsonIgnoreProperties(ignoreUnknown = true, value = 
{"hibernateLazyInitializer", "handler", "fieldHandler"})
public class Author{
... ...

Author類中屬性上註解,此屬性Book中引用了private Set authors;

public class Author{
... ...
@JsonIgnoreProperties(ignoreUnknown = true, value = {"authors"})
private Set<Book> books;
... ...

總結: 本實體中引入了另外一個實體,但另外一個實體也引用了自己無論是集合還是單個實體。jakson在格式化資料的時候會動態過濾掉此屬性中對本身物件的引用。