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.