Jpa实体关系造成无穷无尽的循环

时间:2017-10-12 02:50:54

标签: json spring jackson

我使用spring数据jpa来构建我的项目。有一个用户实体和一个商务实体。

@ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private UserInformation belongUser;//所属用户

上面的代码是Biz类的一部分。

@OneToMany(cascade = CascadeType.ALL,mappedBy = "belongUser")
private Set<BizInformation> bizs = new HashSet<BizInformation>();

这是User class的一部分

问题是当我通过RESTful api获得UserInfomation时,它返回一个BizInfo,然后在BizInfo中返回UserInfomation,最后导致StackOverFlow异常。

我该如何解决这个问题?感谢。

2 个答案:

答案 0 :(得分:3)

这个问题是由双向关系引起的。您可以使用 @JsonManagedReference @JsonBackReference

  • @JsonManagedReference是引用的前沿部分 - 那个 正常序列化。
  • @JsonBackReference是引用的后半部分 - 它将被省略 来自序列化。

在您的情况下,您可以在User类

中添加@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL,mappedBy = "belongUser")
@JsonManagedReference
private Set<BizInformation> bizs = new HashSet<BizInformation>();

和@JsonBackReference for Biz类将省略UserInformation序列化

@ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
@JsonBackReference
private UserInformation belongUser;//所属用户

您还可以将@JsonIgnore用于要省略序列化的类

更多细节:jackson-bidirectional-relationships-and-infinite-recursion

答案 1 :(得分:2)

另一种方法是使用@JsonIgnoreProperties

@JsonIgnoreProperties("bizs")
@ManyToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
private UserInformation belongUser;