Home > Blockchain >  Why does the mappedBy parameter cause infinite recursion in spring boot?
Why does the mappedBy parameter cause infinite recursion in spring boot?

Time:01-03

These are two entities, each with more fields but these two are causing StackOverflow. When I'm using only @JsonMannagedReference and @JsonBackReference and not using mappedBy, infinite recursion doesn't exist. Still, in that case, I'm unable to create bidirectional relation, when I add a mappedBy parameter it causes a StackOverflow error.

@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor

public class Business {

@OneToMany(targetEntity = ProductCategory.class
            , cascade = CascadeType.ALL
            , fetch = FetchType.LAZY
            , mappedBy = "business"
    )
    @JsonManagedReference
    private List<ProductCategory> productCategories;
}

@Entity
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor

public class ProductCategory {

@ManyToOne(targetEntity = Business.class
            , cascade = CascadeType.ALL
            , fetch = FetchType.LAZY)
    @JoinColumn(name = "business_id")
    @JsonBackReference
    private Business business;
}

CodePudding user response:

We have a very similar setup and it works. I see two differences.

First, we do not set targetEntity, JPA should be able to figure that out based on field types.

Second, we excluded "business" fields from toString and equalsAndHashCode generated for ProductCategory class.

Try adding annotations

@ToString(exclude = {"business"})
@EqualsAndHashCode(exclude = {"business"})

to your ProductCategory class.

That should exclude cyclic calls in toString and equals/hashcode methods and take away your unwanted infinite recursion.

CodePudding user response:

This error can occur when you are serializing an object to JSON and the object has a bidirectional relationship with another object, causing an infinite loop.

To fix this error, you need to use the mappedBy attribute in the @OneToMany and @ManyToOne annotations to specify the field in the other object that is the inverse of the relationship. This will allow Jackson (the JSON serialization library that these annotations are part of) to correctly handle the bidirectional relationship and avoid the StackOverflow error.

For example:

class A {
   @JsonManagedReference
   @OneToMany(mappedBy = "a")
   private List<B> bList;
   // other fields and methods
}

class B {
   @JsonBackReference
   @ManyToOne
   private A a;
   // other fields and methods
}

In this example, A has a one-to-many relationship with B, and B has a many-to-one relationship with A. The mappedBy attribute in the @OneToMany annotation specifies that the a field in B is the inverse of the relationship. The @JsonBackReference annotation on the a field in B indicates that this field should not be serialized, to avoid the infinite loop.

  • Related