I need to get simple List of Parent objects with null values for childs. But when i use findAll() method and then try to get child object i get LazyInitializationException: failed to lazily initialize a collection of role: ... could not initialize proxy - no Session I see explanation of this problem (about Lazy/Eager, JOIN FETCH), but i need to get null for child objects without query for childs.
@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();
}
In hibernate i get correct query:
select parent0_.id as id1_0_ from parent parent0_
Before test i add few parent entities in DB, result not empty, and on this test i get error LazyInitializationException
@Test
public void checkParentListFormat() {
List<Parent> parentList = parentService.getParentList();
Assertions.assertThat(parentList.get(0).getChilds()).isNull();
}
I read about DTO, but is it possible to get simple Entity with null values? Thanks
I think you need to put your lazy initialization in the parent annotation.