有这样三个类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 思否