【发布时间】:2022-10-24 03:41:17
【问题描述】:
有两个实体:
class Entity1{
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "entity1Id", unique = true, nullable = false)
private Integer entity1Id;
@OneToMany(mappedBy = "entity1", cascade=CascadeType.ALL,fetch=FetchType.EAGER)
Set<Entity2> entity2set = new Hashset<>();
}
class Entity2 {
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "entity1Id")
private Entity1 entity1;
}
无论我如何使用 @JsonIgnore 或 @JsonIgnoreProperties 注释这些字段,当我尝试执行以下操作时仍然会得到无限递归:
Entity1 entity1 = dao.saveEntity1(fields...);
String json = new ObjectMapper().writeValueAsString(entity1);
org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: org.hibernate.Entity1["entity2set"]->org.hibernate.collection.internal.PersistentSet[0]->gis.hibernate.Entity2["entity1"]->gis.hibernate.Entity1["entity2set"]->org.hibernate.collection.internal.PersistentSet[0]-> ...
我究竟做错了什么?以下是我尝试过的尝试:
@JsonIgnoreProperties("entity1")
private Set<Entity2> entity2set = new HashSet<>();
together with
@JsonIgnoreProperties("entity2set")
private Entity1 entity1;
@JsonIgnore
private Entity1 entity1; (inside Entity2)
@JsonIgnore
private Set<Entity2> entity2set = new HashSet<>(); (inside Entity1)
我究竟做错了什么?
【问题讨论】:
-
@SternK 实际上没有,我也尝试过 JsonManagedReference 和 JsonBackReference。对象映射器仍然获得无限递归。我不明白..
标签: java hibernate serialization infinite-recursion