How to make both bidirectional hiberbate entities serialized

两盒软妹~` 提交于 2021-01-28 05:20:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!