Spring Hibernate Bidirectional ManyToMany StackOverflowError

匿名 (未验证) 提交于 2019-12-03 01:41:02

问题:

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?

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!