java - spring mvc 4 在无限循环中返回JSON

标签 java spring spring-mvc

实体:

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/

相关文章:

java - 为什么我总是得到-1作为in.read(buf)的值?

java - 提交到 ExecutorService 后修改可运行对象?

java - 以 "@"开头的 Spring 变量

java - NoSuchBeanDefinitionException : No qualifying bean of type JpaVendorAdapter found for dependency

java - 使用 Spring JavaMailSender 将文件作为附件或内联发送

java - Null Exception 从下拉列表中保存值

java - 如何使用 Eclipse 在 Java GUI JTextArea 中滚动?

java - 来自 Spring MVC Controller 的异步调用

java - 将集合绑定(bind)到表单 - 为什么它不起作用?

java - 如何不通过引用将元素从 ArrayList 复制到另一个?