指定是否使用Spring Data延迟加载

coo*_*ist 4 java spring hibernate jpa spring-data

我在实体中有一个懒惰的fetch类型集合.我正在使用Spring Data(JpaRepository)来访问实体.

@Entity
public class Parent{
@Id
private Long id;

    @OneToMany(mappedBy = "parentId", fetch = FetchType.LAZY)
    private Set<Child> children;
}
Run Code Online (Sandbox Code Playgroud)

我想在服务类和当前实现中有两个函数如下:

  1. 获取父级时,"children"应为null

    public Parent getParent(Long parentId){
        return repo.findOne(parentId);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 取得父母时应填写"子女":

     public Parent getParentWithChildren(Long parentId){
         Parent p = repo.findOne(parentId);
         Hibernate.initialize(p.children);
         return p;
    }
    
    Run Code Online (Sandbox Code Playgroud)

从RestController返回"Parent"实体时,抛出以下异常:

@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
}
Run Code Online (Sandbox Code Playgroud)

org.springframework.http.converter.HttpMessageNotWritableException:无法写内容:懒得初始化角色集合:com.entity.Parent.children,无法初始化代理 - 无会话(通过引用链:com.entity.Parent [ "孩子们"]); 嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:懒得初始化一个角色集合:com.entity.Parent.children,无法初始化代理 - 没有Session(通过引用链:com.entity.Parent ["children "])

Ala*_*Hay 6

如果您希望根据用例允许同一域模型的不同JSON表示,那么您可以查看以下内容,这样您就可以在不需要DTO的情况下执行此操作:

https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

或者,另请参阅下面的"Spring Data REST中的预测"部分

https://spring.io/blog/2014/05/21/what-s-new-in-spring-data-dijkstra#projections-in-spring-data-rest