Query exception when two-way table association: java.lang.StackOverflowError: null

java.lang.StackOverflowError: null

The reason for the error is a stack overflow.

It is due to an infinite loop or infinite recursion when using Jpa query.

For example, the following two bidirectionally related entity columns:

public class User{
//Other properties and get set methods are omitted
@ManyToMany
@JoinTable(name = "UserRole", joinColumns = { @JoinColumn(name = "userId") }, inverseJoinColumns ={@JoinColumn(name = "roleId") })
private List<Role> roleList;
}

--------

public class Role{
//Other properties are ignored by the get set method
@ManyToMany
@JoinTable(name = "UserRole", joinColumns = { @JoinColumn(name = "roleId") }, inverseJoinColumns ={@JoinColumn(name = "userId") })
private List<Role> userList;
}

When traversing the collection,

for (Role role: user.getRoleList ()) {

        System.out.println(role);

}

When a role object is output, the userlist is also output. Because it is bidirectionally associated, the user object is also triggered, followed by the roleList. . . Generate infinite recursion, resulting in stack overflow.

The solution is:

for (Role role: user.getRoleList ()) {

        role.setUserList(null);//Terminate early so that infinite recursion will not occur

        System.out.println(role);

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324748057&siteId=291194637