问题
I have 2 Entities:
public class Restaurant {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "restaurant")
private Set<Vote> votes;
}
and
public class Vote {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "restaurant_id", nullable = false)
private Restaurant restaurant;
}
if I try to get both of them like that
@Query("SELECT r FROM Restaurant r JOIN FETCH r.vote ")
I get Infinite Recursion with Jackson JSON. So I managed to find a way to handle that:
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;
}
Now I can get restaurant with votes like that?
@Query("SELECT r FROM Restaurant r JOIN FETCH r.vote ")
But now I CAN'T GET Votes with restaurant
@Query("SELECT v FROM Vote v JOIN FETCH v.restaurant ")
because @JsonBackReference meant
private Restaurant restaurant;
wont be serialized. But i need both of this bidirectional relationship in my controllers. What should i do?
回答1:
For serialization of entities with bidirectional relationship use @JsonIdentityInfo
and remove the @JsonBackReference
and @JsonManagedReference
. The property of the @JsonIdentityInfo
refer to your entity id
property used to identify entity.
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Restaurant {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Vote {
来源:https://stackoverflow.com/questions/61775479/how-to-make-both-bidirectional-hiberbate-entities-serialized