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.

4
  • Please post your query that fetches the parent. Commented Dec 15, 2016 at 4:04
  • 1
    @AbdullahWasi it is just the standard findAll query, and is being called form JAX-RS as a named query Commented Dec 15, 2016 at 4:05
  • Lazy loading is the default so if they are being loaded then it is your code that it is doing it - so post the relevant code. Commented Dec 15, 2016 at 9:18
  • Did you find any solution for this fetching parent without children? Commented Sep 12, 2019 at 22:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

MapStruct is also very efficient, check this answer that prevent the same problem : stackoverflow.com/a/65391112/2641426

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.