【发布时间】:2020-04-28 20:40:50
【问题描述】:
我尝试使用 spring 在两个实体之间创建简单的关系。有一个 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;
}
}
当我尝试在 @RestController 中查找带有 this.profileRepository.findById(id).get() 的个人资料时,我收到此错误:
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.
谁能向我解释为什么这不起作用?我跟着this教程。
【问题讨论】:
-
交易已关闭。如果知道需要相关对象,则应该急切地而不是懒惰地获取关系。
-
本教程中没有“其余控制器”(除了存储库...具有“内置”控制器),您可能只是缺少控制器类/方法上的
@Transactional注释(like here) ...advanced issue here
标签: java spring spring-data-jpa spring-rest