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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With