您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Spring Data JPA @OneToOne注释无限递归错误

Spring Data JPA @OneToOne注释无限递归错误

这是一个已知问题,当您具有双向关系时,杰克逊将尝试从另一侧序列化一侧的每个引用,以便逻辑上具有无限递归。

解决方案:有很多解决方案,可以在一侧使用@JsonIgnore以避免序列化带注释的引用,从而破坏了无限递归

 @EqualsAndHashCode(exclude = "husband",callSuper = false)
 @Entity
@Table(name = "t_wife")
public class Wife {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@OneToOne(mappedBy = "wife",cascade = {CascadeType.ALL})
@JsonIgnore
private Husband husband;

//omitted getter/setter
}

您也可以使用@ JsonManagedReference / @ JsonBackReference,请查看此链接获取更多有关如何使用它们的信息

这个答案有一个问题,如果您尝试序列化妻子的方向,您将没有丈夫对象,因为解决方案是避免序列化它。

一个很好的解决方案,它在此链接中提到,其思想是生成对父实体的引用,因此,如果您要序列化丈夫,您将拥有丈夫->妻子-> [引用丈夫而不是丈夫] ,您所需要做的就是使用@JsonIdentityInfo注释您的实体

@EqualsAndHashCode(exclude = "husband",callSuper = false)
@Entity
@Table(name = "t_wife")
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class Wife {

@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
@Entity
@Table(name = "t_husban")
public class Husband {
@Id
dotnet 2022/1/1 18:18:18 有828人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶