如何使两个双向休眠实体都序列化 [英] How to make both bidirectional hiberbate entities serialized

查看:89
本文介绍了如何使两个双向休眠实体都序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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;
}

如果我想让他们两个都这样

if I try to get both of them like that

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

我通过Jackson JSON获得了无限递归.因此,我设法找到一种解决方法:

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 ")

因为@JsonBackReference意味着

because @JsonBackReference meant

private Restaurant restaurant;

将不会序列化.但是我在控制器中需要两个双向关系.我该怎么办?

wont be serialized. But i need both of this bidirectional relationship in my controllers. What should i do?

推荐答案

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

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 {

这篇关于如何使两个双向休眠实体都序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆