0

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"])

K.Nicholas
  • 8,797
  • 4
  • 34
  • 53
FELR54345
  • 1
  • 1
  • 1
    Possible duplicate of [What is lazy loading in Hibernate?](https://stackoverflow.com/questions/2192242/what-is-lazy-loading-in-hibernate) – K.Nicholas May 28 '19 at 22:14
  • @K.Nicholas I have a somewhat understanding about what lazy loading is in Hibernate. The problem I am facing right now is that I am unable to get it to function the way I want it to. – FELR54345 May 28 '19 at 22:16
  • Then you should provide a [MCVE](https://stackoverflow.com/help/minimal-reproducible-example). – K.Nicholas May 28 '19 at 22:19

0 Answers0