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?