如何在Spring Boot JPA中的OneToMany中获取子项的Null值

问题描述

我需要获取具有null值的child的简单Parent对象列表。 但是当我使用findAll()方法,然后尝试获取子对象时,我得到了 LazyInitializationException:无法延迟初始化角色集合:...无法初始化代理-没有会话 我看到了这个问题的解释(关于Lazy / Eager,JOIN FETCH),但是我需要为子对象获取null而不查询子对象。

@Entity
public class Parent {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToMany(mappedBy = "parent")
    Set<Child> childs;

@Entity
public class Child {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_id")
    Parent parent;

@Service
    public class ParentService {

    @Autowired
    ParentRepository parentRepository;

    public List<Course> getParentList() {
        return parentRepository.findAll();
    }

在休眠状态下,我得到正确的查询:

select parent0_.id as id1_0_ from parent parent0_

在测试之前,我在数据库中添加了几个父实体,结果不为空,并且在此测试中,我收到错误LazyInitializationException

@Test
    public void checkParentListFormat() {
        List<Parent> parentList = parentService.getParentList();
        Assertions.assertThat(parentList.get(0).getChilds()).isNull();
    }


我阅读了有关DTO的信息,但是是否可以获取具有空值的简单实体?谢谢

解决方法

我认为您需要将懒惰的初始化放在父批注中。

@OneToMany(mappedBy = "parent",fetch = FetchType.LAZY)
Set<Child> childs;

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...