【发布时间】:2020-09-28 22:35:36
【问题描述】:
我需要为孩子获取具有空值的简单父对象列表。 但是当我使用 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 的信息,但是否可以获得具有空值的简单实体?谢谢
【问题讨论】:
标签: java spring-boot jpa hibernate-onetomany spring-repositories