4

I have a parent like this:

@Entity
@Table(name="parent")
public class Parent {

    private List<Child> childs;
    private List<AnotherChild> anotherChilds;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    public List<Child> getChilds() {
        return childs;
    }

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    public List<AnotherChild> getAntoherChilds() {
        return anotherChilds;
    }

    //Getters and Setters ommited
}

And two children like this

@Entity
@Table(name="child")
public class Child {

    private Parent parent;

    @ManyToOne
    @JoinColumn(name = "column_name")
    public Parent getParent() {
        return patern;
    }
}

@Entity
@Table(name="another_child")
public class AnotherChild {

    private Parent parent;

    @ManyToOne
    @JoinColumn(name = "column_name")
    public Parent getParent() {
        return patern;
    }
}

I have a named query which gets all the Parents, but this is also loading all the children? How can I stop the children for automatically loading?

Thanks.

Nurjan
  • 5,889
  • 5
  • 34
  • 54
iqueqiorio
  • 1,149
  • 2
  • 35
  • 78

1 Answers1

4

I know my answer is late, but it may help others because I had the same problem for a while, based this answer if you use rest API, Spring calls Jackson to return Parent object and Jackson calls getChild, for this reason, parent's child loaded. one solution is to define a Dto class for the Parent class that does not include Child, for example

public class ParentResponseDto{
    private Long id
    private String name; 
    //and your desired attribute that you want to load
}

then in rest controller return ParenResponseDto

@GetMapping
public ParenResponseDto getParent(Long id){
    Parent p = repository.findById(id);
    ParenResponseDto dto = mapParentToParenResponseDto();
    return dto;
}

you can use ModelMapper to map classes, this is a great module

fatemeakbari
  • 141
  • 2
  • 6
  • 1
    **MapStruct** is also very efficient, check this answer that prevent the same problem : https://stackoverflow.com/a/65391112/2641426 – DependencyHell Dec 21 '20 at 10:31