Yuvanath
Yuvanath

Reputation: 127

The Parent entity inside child entity pull the child again

When I try to fetch the child entity, it also gets the parent entity because of one to many bidirectional mapping but the parent entity inside the child again pulling its child. which need to be avoided

Parent entity

@OneToMany(mappedBy = "school", cascade = CascadeType.ALL)
private List<Students> studentsList = new ArrayList<>();

Child Entity

@ManyToOne(optional = false)
@JoinColumn(name = "school_id",referencedColumnName = "id")
private School school;

While I hit the get call of child entity the response is like

{
    "id": 1,
    "firstName": "firstname",
    "lastName": "lastname",
    "age": "20",
    "school": {
        "id": 1,
        "name": "testName",
        "description": "school",
        "studentsList": [
            1
        ]
    }
}

*But the expected response is

{
    "id": 1,
    "firstName": "firstname",
    "lastName": "lastname",
    "age": "20",
    "school": {
        "id": 1,
        "name": "testName",
        "description": "school"
    }
}

Upvotes: 0

Views: 548

Answers (2)

Dushyant Kumar
Dushyant Kumar

Reputation: 21

Use "Eager" fetch.

@OneToMany(fetch = FetchType.EAGER, mappedBy = "school", cascade = CascadeType.ALL)
private List<Students> studentsList = new ArrayList<>();

Upvotes: 0

Chinnappa Raj J
Chinnappa Raj J

Reputation: 101

Understood your problem you may use the @JsonIgnoreProperties({}) Annations.

For Example:
In parent Object like this

@OneToMany(mappedBy = "school", cascade = CascadeType.ALL)
@JsonIgnoreProperties({"school"})
private List<Students> studentsList = new ArrayList<>();

Upvotes: 1

Related Questions