如何解决如何在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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。