Home > Net >  Getting infinite recursion with ObjectMapper even though entities' fields are annotated with @J
Getting infinite recursion with ObjectMapper even though entities' fields are annotated with @J

Time:10-24

Got two entities:

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

No matter how I annotate those fields with @JsonIgnore or @JsonIgnoreProperties, I still get infinite recursion when I try to:

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]-> ...

What am I doing wrong? Here are the attempts that I tried:

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

What am I doing wrong?

CodePudding user response:

You are using @JsonIgnoreProperties incorrectly. It is supposed to be on the class level.

CodePudding user response:

I've solved with JsonView and with

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

This was the only thing that worked for me

  • Related