JPA many-to-many relationship causing infinite recursion and stack overflow error

后端 未结 2 648
青春惊慌失措
青春惊慌失措 2021-02-10 02:02

I\'m working on an EclipseLink project in which one user can \"follow\" another as can be done on social media sites. I have this set up with a User entity (referen

2条回答
  •  不要未来只要你来
    2021-02-10 02:38

    I tried everything what I found in the web and it didn't work. None of any annotation. But I found a solution after a huge fight with this issue.

    First point you need to add to both entities (not the relational one) this annotation:

    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "relationClass"})
    public class YourClass { ...
    }
    

    Where "relationClass" is the name of the List/Set of your class for the relations:

    For example:

      @OneToMany(mappedBy = "yourClass", cascade = CascadeType.ALL, fetch = FetchType.LAZY,  orphanRemoval = true)
        private Set relationClass;
    

    You also need to specify "hibernateLazyInitializer", "handler" in the annotation or it will cause serialization problem.

    After it if you see the table that define relation table and you will see rows in there, and in your JSON response will not be any loop anymore. So as I think the best solution is also create a repository for the relation tablee and access the data from there.

    Hope it will help someone!

提交回复
热议问题