Spring JPA with nested relation but just need 1 depth relation

39 views Asked by At

I made 2 depth relations for MainBranch model and when I get the MainBranch it will get SubBranch and SubBranchRef. I need to get just MainBranch with SubBranch. What should I do about this problem?

public class MainBranch{

    @Column(name = "name", nullable = false, length = 100)
    private String name;

    @OneToMany(mappedBy = "mainBranch")
    @JsonManagedReference
    private List<SubBranch> subBranchs = new ArrayList<>();
}


public class SubBranch{
    @Column(name = "name", nullable = false, length = 100)
    private String name;

    @ManyToOne
    @JsonBackReference
    @JoinColumn(name = "main_branch_id", nullable = false)
    private MainBranch mainBranch;

    @OneToMany(mappedBy = "subBranch")
    @JsonManagedReference
    private List<SubBranchRef> subBranchRef = new ArrayList<>();

}

public class SubBranchRef{

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "sub_branch_id", nullable = false)
    @JsonBackReference
    private SubBranch subBranch;

    @Column(name = "ref_data", nullable = false, length = 200)
    private String refData;

}
2

There are 2 answers

0
Malvin Lok On

Maybe use FetchType.LAZY for SubBranchRef in SubBranch entity:

By making the FetchType as LAZY, this would not load SubBranchRef when we fetch the SubBranch.

public class SubBranch{
    ...
    @OneToMany(mappedBy = "subBranch", fetch = FetchType.LAZY)
    @JsonManagedReference
    private List<SubBranchRef> subBranchRef = new ArrayList<>();
    ...
}
0
raiwaqar On

All you need to add @JsonIgnoreProperties on subBranchs in MainBranch

@OneToMany(mappedBy = "mainBranch")
@JsonManagedReference
@JsonIgnoreProperties(value = {"subBranchRef"}, allowSetters = true)
private List<SubBranch> subBranchs = new ArrayList<>();