我有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 {