Я пытаюсь создать простые отношения между двумя сущностями с пружиной. Существует одна User
сущность, которая содержит много profile
сущностей.
Пользовательский объект
@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;
}
}
Профиль объекта
@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;
}
}
Когда я пытаюсь найти профиль с this.profileRepository.findById(id).get()
внутри @RestController
Я получаю эту ошибку:
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.
Может кто-нибудь объяснить мне, почему это не работает? Я следовал этому учебнику.