当前位置:   article > 正文

Spring Boot JPA外键存在时的循环调用异常_jpa中有外键查询为何会不停查询

jpa中有外键查询为何会不停查询

有这样三个类UnicastFlow, SinglePath, HopInfo,其间存在关联关系。

  1. @ToString(callSuper = true)
  2. @Getter @Setter
  3. @Entity
  4. // @Table(name = "flow")
  5. @DiscriminatorValue("unicast_flow")
  6. @NoArgsConstructor
  7. // @AllArgsConstructor
  8. public class UnicastFlow extends AbstractFlow{
  9. private String sourceMacAddr;
  10. private int sourcePortInd;
  11. private String destMacAddr;
  12. private int destPortInd;
  13. @OneToOne(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
  14. @JoinColumn(name = "path_id")
  15. // @JsonManagedReference
  16. private SinglePath routePath; // In terms of mac address
  17. }
  18. @Getter
  19. @Setter
  20. @Entity
  21. @Table(name = "path")
  22. public class SinglePath {
  23. @Id
  24. @GeneratedValue(strategy = GenerationType.IDENTITY)
  25. Integer id;
  26. @OneToOne(cascade = CascadeType.ALL, mappedBy = "routePath")
  27. // @JsonBackReference
  28. UnicastFlow unicastFlow;
  29. @OneToMany(targetEntity = HopInfo.class, cascade = CascadeType.ALL, mappedBy = "pathId", fetch= FetchType.EAGER)
  30. @OrderBy("id ASC") // 按照ID升序
  31. // @JsonManagedReference
  32. List<HopInfo> pathInfo;
  33. }
  34. @Getter @Setter
  35. @NoArgsConstructor
  36. @Entity
  37. @Table
  38. @JsonIgnoreProperties({"handler", "hibernateLazyInitializer"})
  39. public class HopInfo {
  40. @Id
  41. @GeneratedValue(strategy = GenerationType.IDENTITY)
  42. Integer id;
  43. String devAlias;
  44. int portInd;
  45. int queueInd;
  46. long openTime;
  47. long closeTime;
  48. @ManyToOne(targetEntity = SinglePath.class, cascade = CascadeType.ALL,fetch = FetchType.EAGER)
  49. @JoinColumn(name = "path_id")
  50. // @JsonBackReference
  51. SinglePath pathId;
  52. }

如此进行jpa findAll调用时,报如下错:

2022-05-20 15:23:30.896 ERROR 17272 --- [nio-8443-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: ....

产生了死循环,要解决该问题,需要分别在外键及对应的类上分别加上@JsonManagedReference,@JsonBackReference注解即可解决。

参考:Spring Boot QuickStart (5) - Spring Data JPA - SegmentFault 思否

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/1009377
推荐阅读
相关标签
  

闽ICP备14008679号