1

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

Pavel Verhoturov
  • 51
  • 1
  • 1
  • 4

1 Answers1

0

I think you need to put your lazy initialization in the parent annotation.

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
Set<Child> childs;
Nick H
  • 8,897
  • 9
  • 41
  • 64
  • Yes, i tried this, but situation not change. For oneToMany default fetch type is Lazy and when set Lazy directly nothing changes. I see similar questions and it seems that if object has childs there is no way to get them without different object (DTO). For example, i need ParentDTO object with only parentId field. In this case i will get what i need. – Pavel Verhoturov Sep 29 '20 at 09:06
  • So, i need to Fetch all childs or create different object (DTO) with fields i need and get this object. If anyone knows how to stop hibernate try get child in selected query it will be great. For now i will use DTO. – Pavel Verhoturov Sep 29 '20 at 09:13