0

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?

SternK
  • 11,649
  • 22
  • 32
  • 46
Marco
  • 322
  • 1
  • 3
  • 15
  • Does this answer your question? [Infinite Recursion with Jackson JSON and Hibernate JPA issue](https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue) – SternK Oct 19 '22 at 09:18
  • @SternK actually no, I also tried JsonManagedReference and JsonBackReference. Object Mapper still getting infinite recursion. I don't understand.. – Marco Oct 19 '22 at 09:32

2 Answers2

0

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

0

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

Marco
  • 322
  • 1
  • 3
  • 15