Search code examples
javaspringspring-data-jpaspring-rest

Spring One-To-Many relationship throws Exception : org.springframework.http.converter.HttpMessageNotWritableException


I try to create a simple relationship between two entities with spring. There is one User entity that holds many profile entities.

User Entity

@Entity
public class User {

    @OneToMany(mappedBy = "user")
    private List<Profile> profiles;

    public List<Profile> getProfiles() {
        return profiles;
    }

    public void setProfiles(List<Profile> profiles) {
        this.profiles = profiles;
    }
}

Profile Entity

@Entity
public class Profile {

    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

When I try to find a profile with this.profileRepository.findById(id).get() inside a @RestController I get this error:

org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: failed to lazily initialize a collection of role: User.profiles, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: User.profiles, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->User["profiles"])]
The server encountered an unexpected condition that prevented it from fulfilling the request.

Can anyone explain to me why this is not working? I followed this tutorial.


Solution

  • as Mandar said, you can resolve it by eager fetch. But if you don't want to fetch all I mean eager fetch, then you have to initialize them for lazy fetch like this to the related class, your Profile class:

    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    @Entity
    public class Profile implements Serializable{
    //
    //
    .. your other stuffs
    }
    

    Edit: also change your User entity like this:

    @Entity
    public class User implements Serializable{
    
        @OneToMany(mappedBy = "user")
        private List<Profile> profiles = new LinkedHashSet<Profile>();
    //...other stufs..
    .
    .
    }
    

    Hope, this will help!