指定是否延迟加载Spring数据 [英] Specifying whether or not to lazily load with Spring Data

查看:182
本文介绍了指定是否延迟加载Spring数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a lazy fetch type collection in an entity. And I am using Spring Data (JpaRepository) for accessing the entities.

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

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

我希望服务类和当前实现中的两个函数如下所示: p>

I want two functions in service class and current implementation are as following:


  1. 当获取父项时,children应为null

  1. "children" should be null when fetching parent

public Parent getParent(Long parentId){
    return repo.findOne(parentId);
}


  • 在获取父项时应填写children:

  • "children" should be filled when fetching parent:

     public Parent getParentWithChildren(Long parentId){
         Parent p = repo.findOne(parentId);
         Hibernate.initialize(p.children);
         return p;
    }
    


  • 一个来自RestController的实体,抛出异常:

    When returning "Parent" entity from a RestController, following exception is thrown:

    @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:
    无法写入内容:无法懒惰地初始化
    集合的作用:c​​om.entity.Parent.children,无法初始化代理 - no
    Session(通过引用链:com.entity.Parent [children]);
    嵌套异常是
    com.fasterxml.jackson.databind.JsonMappingException:未能延迟
    初始化角色集合:com.entity.Parent.children,不能
    初始化代理 - 没有会话(通过引用链:
    com.entity.Parent [children])

    org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: com.entity.Parent.children, could not initialize proxy - no Session (through reference chain: com.entity.Parent["children"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.entity.Parent.children, could not initialize proxy - no Session (through reference chain: com.entity.Parent["children"])


    推荐答案

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

    If you are looking to allow for different JSON representations of the same domain model depending on use case, then you can look at the following which will allow you to do so without requiring DTOs:

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

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

    Alternatively, see also the 'Projections in Spring Data REST' section in the following

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

    这篇关于指定是否延迟加载Spring数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆