Search code examples
javaspring-boothibernatespring-data-jpahibernate-mapping

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

Solution

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