【问题标题】:Getting infinite recursion with ObjectMapper even though entities' fields are annotated with @JsonIgnore使用 ObjectMapper 获得无限递归,即使entities\' 字段使用@JsonIgnore 注释
【发布时间】: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)

我究竟做错了什么?

【问题讨论】:

标签: java hibernate serialization infinite-recursion


【解决方案1】:

您错误地使用了@JsonIgnoreProperties。应该是班级层面的。

【讨论】:

  • 还是行不通
【解决方案2】:

我已经用 JsonView 和

String json = new ObjectMapper().writerWithView(MyView.class).writeValueAsString(entity);

这是唯一对我有用的东西

【讨论】:

    猜你喜欢
    • 2016-06-10
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2014-05-03
    • 1970-01-01
    • 2015-10-19
    • 2013-01-31
    相关资源
    最近更新 更多