简体   繁体   中英

How get Null value for child in OneToMany in Spring Boot JPA

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.

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
Set<Child> childs;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM