【发布时间】:2015-05-07 21:51:12
【问题描述】:
我在实体中有一个惰性获取类型集合。我正在使用 Spring Data (JpaRepository) 来访问实体。
@Entity
public class Parent{
@Id
private Long id;
@OneToMany(mappedBy = "parentId", fetch = FetchType.LAZY)
private Set<Child> children;
}
我想要服务类中的两个函数,当前实现如下:
-
“children”在获取父级时应该为空
public Parent getParent(Long parentId){ return repo.findOne(parentId); } -
"children" 取父时要填写:
public Parent getParentWithChildren(Long parentId){ Parent p = repo.findOne(parentId); Hibernate.initialize(p.children); return p; }
当从 RestController 返回“父”实体时,抛出以下异常:
@RequestMapping("/parent/{parentId}")
public Parent getParent(@PathVariable("parentId") Long id)
{
Parent p= parentService.getParent(id);//ok till here
return p;//error thrown when converting to JSON
}
org.springframework.http.converter.HttpMessageNotWritableException: 无法写入内容:未能延迟初始化集合 角色:com.entity.Parent.children,无法初始化代理 - 否 会话(通过引用链:com.entity.Parent["children"]); 嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: 懒惰失败 初始化角色集合:com.entity.Parent.children,不能 初始化代理 - 无会话(通过引用链: com.entity.Parent["children"])
【问题讨论】:
标签: java spring hibernate jpa spring-data