Home > OS >  The Parent entity inside child entity pull the child again
The Parent entity inside child entity pull the child again

Time:01-31

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"
    }
}

CodePudding user response:

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<>();

CodePudding user response:

Use "Eager" fetch.

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

  •  Tags:  
  • Related