我尝试使用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;
}
}
[当我尝试在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.
有人可以向我解释为什么这行不通吗?我遵循了this教程。
如果您知道每次检索用户都希望查看所有配置文件,然后将字段注释更改为:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade =CascadeType.ALL
private List<Profile> profiles; = new LinkedHashSet<Profile>();
默认情况下,集合是延迟加载的,如果想了解更多,请查看this。
如Mandar所说,您可以通过eager fetch
来解决。但是,如果您不想获取我的全部意思eager fetch
,则必须将它们初始化为类似相关对象的Profile类的惰性获取:
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@Entity
public class Profile implements Serializable{
//
//
.. your other stuffs
}
[Edit:也会这样更改您的User实体:
@Entity
public class User implements Serializable{
@OneToMany(mappedBy = "user")
private List<Profile> profiles = new LinkedHashSet<Profile>();
//...other stufs..
.
.
}
希望,这会有所帮助!