如何使两个双向休眠实体序列化

How to make both bidirectional hiberbate entities serialized

我有 2 个实体:

public class Restaurant {
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "restaurant")
  private Set<Vote> votes;
}

public class Vote {
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "restaurant_id", nullable = false)
  private Restaurant restaurant;
}

如果我试着让他们都那样

@Query("SELECT r FROM Restaurant r JOIN FETCH r.vote ")

我得到了 Jackson JSON 的无限递归。所以我设法找到了一种方法来处理这个问题:

public class Restaurant {
  @JsonManagedReference
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "restaurant")
  private Set<Vote> votes;
}

public class Vote {
  @JsonBackReference
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "restaurant_id", nullable = false)
  private Restaurant restaurant;
}

现在我可以用这样的票去餐厅吗?

@Query("SELECT r FROM Restaurant r JOIN FETCH r.vote ")

但现在我无法获得餐厅的投票

@Query("SELECT v FROM Vote v JOIN FETCH v.restaurant ")

因为@JsonBackReference 的意思是

private Restaurant restaurant;

不会连载。但是我的控制器中需要这两种双向关系。我该怎么办?

对于具有双向关系的实体的序列化,使用 @JsonIdentityInfo 并删除 @JsonBackReference@JsonManagedReference@JsonIdentityInfo 的 属性 引用了您的实体 id 属性 用于标识实体。

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Restaurant {

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Vote {