实体:
class A{
private int id;
@oneToMany(mappedBy = "a")
private List<B> bList;
}
class B{
private int id;
@ManToOne
private A a;
}
存储库:
interfase BRepository{
@Query("select b from B b where b.a.id = ?1")
public List<B> getB(String id);
}
Controller :
private BRepository b;
@RequestMapping("/b")
public Object getB(){
return b.getB(1);
}
无限循环返回 JSON。
在A类上使用@JsonBackReference注解,结果正常:
class A{
private int id;
@oneToMany(mappedBy = "a")
@JsonBackReference //this property is ignored
private List<B> bList;
}
但是当你查询一个类时,返回的结果不是bList(使用@JsonBackference),我该怎么做才能返回bList属性?
最佳答案
我建议不要在the following reasons的对象之间使用循环引用。 .
这会产生很多问题,JSON 生成就是其中之一。
•Circular class references create high coupling; both classes must be recompiled every time either of them is changed.
•Circular assembly references prevent static linking, because B depends on A but A cannot be assembled until B is complete.
•Circular object references can crash naïve recursive algorithms (such as serializers, visitors and pretty-printers) with stack overflows. The more advanced algorithms will have cycle detection and will merely fail with a more descriptive exception/error message.
•Circular object references also make dependency injection impossible, significantly reducing the testability of your system.
•Objects with a very large number of circular references are often God Objects. Even if they are not, they have a tendency to lead to Spaghetti Code.
•Circular entity references (especially in databases, but also in domain models) prevent the use of non-nullability constraints, which may eventually lead to data corruption or at least inconsistency.
•Circular references in general are simply confusing and drastically increase the cognitive load when attempting to understand how a program functions.
关于java - spring mvc 4 在无限循环中返回JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35647297/