Nick Kulese
Nick Kulese

Reputation: 83

Spring Hibernate Bidirectional ManyToMany StackOverflowError

I'm trying to build bidirectional ManyToMany association.

So, I have an entity called User:

import lombok.Data;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Data
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @ManyToMany(mappedBy="users")
    private List<Chat> chats = new ArrayList<>();
}

And another one called Chat:

import lombok.Data;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Data
@Entity
public class Chat {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;

    @ManyToMany
    @JoinTable(name = "chat_user",
        joinColumns = { @JoinColumn(name = "fk_chat") },
        inverseJoinColumns = { @JoinColumn(name = "fk_user") })
    private List<User> users = new ArrayList<>();
}

So, when I'm trying to do:

Chat chat = new Chat();
User user = new User();

user.getChats().add(chat);
chat.getUsers().add(user); // Getting an exception!!!

Getting this one:

Method trew 'java.lang.StackOverflowExceptionError' exception.
Cannot evaluate hello.models.Chat.toString()

I think the problem is: Chat has user, that refences to that Chat that has user that references to that Chat again and so on.

So how can I solve it?

Upvotes: 0

Views: 1364

Answers (1)

MyTwoCents
MyTwoCents

Reputation: 7624

Yes, you are right with never-ending recursion.

How do we solve this problem? Can try these steps

1 . If you have used toString() in mentioned entities, remove reference of other entity from it.

2 . Can add @JsonIgnore at one side of relation which will break the chain

    @ManyToMany(mappedBy="users")
    @JsonIgnore
    private List<Chat> chats = new ArrayList<>();

Refer to this article for more ways

3 . I notice you are using Lombok, in that case, exclude attribute of the toString annotation and may be can write custom toString keeping point 1 in mind.

Upvotes: 2

Related Questions