JPA many to many relationship causing infinite recursion

Tags: , , , ,



Edit: I solved the problem using @JsonIgnoreProperties in both classes

@JsonIgnoreProperties("pokemons")
@ManyToMany
@JoinTable(
    name = "pokemon_types",
    joinColumns = @JoinColumn(name = "pokemon_id"),
    inverseJoinColumns = @JoinColumn(name = "type_id"))
private Set<Type> types;


@JsonIgnoreProperties("types")
@ManyToMany(mappedBy = "types")
Set<Pokemon> pokemons;

I have two entities in my api. Pokemon which has a list of “types” that pokemon have and Type which has a list of “pokemon” that have that specific type. I’m trying to implement a getAll method in my controllers but i’m having an infinite recursion problem.

I’ve tried to use the @JsonIgnore annotation in my type class but with this i’m not able to get the list of pokemons inside each type. The other side of the relashionship works well.

Is there any way to avoid the infinite recursion problem and at the same time get both lists of the relashionship.

My repositories extend the JpaRepository and my controllers just call the findAll method of the JpaRepository.

Pokemon:

@Getter @Setter @NoArgsConstructor @AllArgsConstructor
@Entity
@Table(name="pokemons")
public class Pokemon implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    
    private String url;
    
    private String img;
    
    @ManyToMany
    @JoinTable(
        name = "pokemon_types",
        joinColumns = @JoinColumn(name = "pokemon_id"),
        inverseJoinColumns = @JoinColumn(name = "type_id"))
    private Set<Type> types;
    
}

Type:

@Setter @Getter @NoArgsConstructor @AllArgsConstructor
@Entity
@Table(name="types")
public class Type implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    
    private String name;
    
    @JsonIgnore
    @ManyToMany(mappedBy = "types")
    Set<Pokemon> pokemons;

}

Expected result:

[
   {
      id: ...,
      name: ...,
      pokemons: [
         {
            id: ...,
            name; ...
            url: ...
            img: ...
         },
         .
         .
         .
      ]
   },
   .
   .
   .
]

Actual result:

[
   {
      id: ...,
      name: ...,
   },
   .
   .
   .
]

Answer

I suggest using @JsonManagedReference @JsonBackReference (latter to be used on the child entity) from the com.fasterxml.jackson.annotation package.

Also explained here: https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion section 3



Source: stackoverflow