[英]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.