Spring Boot JPA外键存在时的循环调用异常

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

@ToString(callSuper = true)
@Getter @Setter
@Entity
// @Table(name = "flow")
@DiscriminatorValue("unicast_flow")
@NoArgsConstructor
// @AllArgsConstructor
public class UnicastFlow extends AbstractFlow{
    private String sourceMacAddr;
    private int sourcePortInd;
    private String destMacAddr;
    private int destPortInd;
    @OneToOne(cascade = CascadeType.ALL, fetch= FetchType.EAGER)
    @JoinColumn(name = "path_id")
    // @JsonManagedReference
    private SinglePath routePath; // In terms of mac address
}

@Getter
@Setter
@Entity
@Table(name = "path")
public class SinglePath {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer id;
    @OneToOne(cascade = CascadeType.ALL, mappedBy = "routePath")
    // @JsonBackReference
    UnicastFlow unicastFlow;
    @OneToMany(targetEntity = HopInfo.class, cascade = CascadeType.ALL, mappedBy = "pathId",  fetch= FetchType.EAGER)
    @OrderBy("id ASC")  // 按照ID升序
    // @JsonManagedReference
    List<HopInfo> pathInfo;
}


@Getter @Setter
@NoArgsConstructor
@Entity
@Table
@JsonIgnoreProperties({"handler", "hibernateLazyInitializer"})
public class HopInfo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Integer id;
    String devAlias;
    int portInd;
    int queueInd;

    long openTime;
    long closeTime;
    @ManyToOne(targetEntity = SinglePath.class, cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinColumn(name = "path_id")
    // @JsonBackReference
    SinglePath pathId;

}

如此进行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 思否

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值