Currently I am developing a social media platform that has an user entity. In this entity I want to add two collections that represent the users that are following the current user and a separate collection of which users the user is following.
The problem I was facing was with the recursive nature of the collections when applying no type of lazy loading which causes a stack overflow.
The software is developed using JPA and JAX-RS. When testing to retrieve the entity I am facing with the problem that the lazy loading of the two collections go wrong.
I tried changing the relationships between the entities multiple times and tried changing the fetch type but that did not help.
public class User implements Serializable {
public static final String TABLE_NAME = "users";
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false, columnDefinition = "bit default 0")
private boolean isAdmin;
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<User> following = new ArrayList<>();
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "following")
private List<User> followers = new ArrayList<>();
}
When trying to get the entity through the REST API with Postman I get the following error:
org.jboss.resteasy.spi.UnhandledException: com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: jea.kwetter.backend.domain.User.following, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->domain.User["following"])