2016-12-27 39 views
1

創建在線商店。我需要生成代表分類樹的json,但是當我生成它時,得到了StackOverflowError。 類別實體:生成json樹時出現StackOverflowError

@OneToMany 
@JoinColumn(name = "parent_category_id") 
private List<Category> subcategories; 


@ManyToOne 
@JoinColumn(name = "parent_category_id") 
private Category parentCategory; 

Json的生成方法,我送列表從控制器到代表樹

@Override 
public List<Category> getCategoryTree() { 
    List<Category> categories = categoryDao.findAll(); 
    List<Category> roots = categories.stream() 
      .filter(category -> category.getParentCategory()!=null) 
      .collect(Collectors.toList()); 
    return roots; 
} 

我猜它,因爲孩子得到父母和父母獲得孩子。但我不能放置@JsonIgnore註釋,因爲那麼它將只寫沒有孩子的父母或沒有父母的所有孩子的列表,是否必須有一種方法來生成json

回答

0

解決方案非常簡單,StackOverflowErrorwas因爲孩子正在生成父母和父母生成子,解決方案是很簡單的細節,註釋 @JsonBackReference

實體:

@OneToMany 
@JoinColumn(name = "parent_category_id") 
private List<Category> subcategories; 


@ManyToOne 
@JsonBackReference 
@JoinColumn(name = "parent_category_id") 
private Category parentCategory; 

的Json樹生成方法:

@Override 
public List<Category> getCategoryTree() { 
    List<Category> categories = categoryDao.findAll(); 
    List<Category> roots = categories.stream() 
      .filter(category -> category.getParentCategory()==null) 
      .collect(Collectors.toList()); 
    return roots; 
}