Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 (referencing a table called users) which has a list of "followers" (users who follow that user) and another list of "following" (users that user is following). The relationship is defined in a separate table called followers which contains columns for the followed user's ID (user_id) and the following user's ID (follower_id).

My users model looks like this:

@Entity
@Table(name = "users")
@NamedQuery(name = "User.findAll", query = "SELECT u FROM USER u")
public class User {
    // other attributes
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "follower", joinColumns = @JoinColumn(
        name = "user_id", referencedColumnName = "id"),
    inverseJoinColumns = @JoinColumn(
        name = "follower_id", referencedColumnName = "id"))
    private List<User> followers;

    @ManyToMany(mappedBy = "followers")
    private List<User> following;

    // other getters and setters
    public List<User> getFollowers() {
        return this.followers;
    }

    public List<User> getFollowing() {
        return this.following;
    }
}

The getFollowers() method seems to work fine, but when getFollowing() is called I get a bunch of console spam that culminates in a StackOverflowException:

com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion 
(StackOverflowError) (through reference chain: 
org.eclipse.persistence.indirection.IndirectList[0]-
>org.myproject.model.User["followers"]-
>org.eclipse.persistence.indirection.IndirectList[0]-
>org.myproject.model.User["following"]-
...
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase
.serializeFields(BeanSerializerBase.java:518)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize
(BeanSerializer.java:117)
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer
.serializeContents(IndexedListSerializer.java:94)
at com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer
.serializeContents(IndexedListSerializer.java:21)
...

Please let me know if I should provide more of the stack trace. Any hints?

like image 310
Ecliptica Avatar asked Apr 18 '17 20:04

Ecliptica


1 Answers

Every time you have @OneToMany (a collection) you need to add @JsonIgnore to it or else it will cause an infinite loop which results in a stack overflow exception because it keeps looking up between the parent(the one side) and the child (the many side) For more info on dealing with this kind of problems check this excellent article http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

like image 95
ketrox Avatar answered Nov 14 '22 22:11

ketrox