【发布时间】:2019-07-19 08:39:57
【问题描述】:
我看到这个问题无处不在,虽然我遵循他们的解决方案并解决了我的问题,但我真的不明白发生了什么。我的实体:
@Entity
public class ItemInOrder {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@ManyToOne
Bill bill;
String comment;
}
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class Bill {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
@OneToOne
Table table;
@OneToMany(mappedBy = "bill")
List<ItemInOrder> itemi_vo_naracka = new ArrayList<>();
}
@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class Table {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
@OneToOne
Bill order_na_ovaa_masa;
}
当我调用基本的 JPA 存储库方法来查找所有 ItemsInOrder 时,我的错误出现了:
return itemInOrderService.getAllItemsInOrder();
The exception says that the infinite loop is happening between Table and Bill:
Infinite recursion (StackOverflowError) (through reference chain: bla.bla.domain.Bill["table"]->bla.bla.domain.Table["order_na_ovaa_masa"]-> and so and so on..
-
那么在我添加之前有人可以向我解释发生了什么 @JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id") 在我的实体上方,以及之后发生的事情。
我已经阅读了一些解释,但我并不真正理解所有这些序列化和反序列化发生了什么。如果解释太长,一个指南或链接到一个解释得很好的帖子也可以(对于所有这一切的完整初学者)。谢谢!
【问题讨论】:
-
您指的是这个答案令人困惑吗? stackoverflow.com/questions/45783753/…
-
我主要指的是序列化的基本概念,以及在我的情况下,它是如何从 ItemsInOrder 转到 Table 和 Bill 之间的。
-
这可能比我在评论中解释得更好。 toptal.com/javascript/bidirectional-relationship-in-json
-
基本上,在 Java 中,Bill 有一个对 Table 的引用,反之亦然。两个有引用的对象。反序列化时,Jackson 看到一个带有表的 Bill,并创建一个与旧 Bill 相同的新 Bill,并将其永远提供给表,因为它只是遵循 JSON 的逻辑并且看不到自引用默认。有了这个身份,Jackson 可以将其映射到那个引用,所以 Bill 中的 Table 被映射回原来的 Bill,而不是新的 Bill。希望这个更有意义。
-
另外,来自:stackoverflow.com/questions/37302816/…
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")这也可以替换您当前的@id,因为您的对象已经附加了(希望是唯一的)ID。
标签: java json spring jackson spring-data-jpa