Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA - Only get parent, not children

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.

like image 619
iqueqiorio Avatar asked Sep 06 '25 02:09

iqueqiorio


1 Answers

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

like image 115
fatemeakbari Avatar answered Sep 07 '25 20:09

fatemeakbari