[英]How get Null value for child in OneToMany in Spring Boot JPA
我需要为孩子获取具有空值的简单父对象列表。 但是当我使用 findAll() 方法然后尝试获取子对象时,我得到 LazyInitializationException: failed to lazyly initialize a collection of role: ... could not initialize proxy - no Session 我看到了这个问题的解释(关于 Lazy/Eager, JOIN FETCH),但我需要为子对象获取空值而不查询子对象。
@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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.