Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve circular reference in json serializer caused by Many TO Many hibernate bidirectional mapping?

I am trying to serialize POJO to JSON but stuck in circular reference problem. I know how to handle one to many and reverse relationships using the @JsonBackReference and @JsonManagedReference.

My problem is with bidirectional many-to-many relation(eg a student can have many courses and each course can have many students enrolled), parent references child and child references back to parent and here my serializer dies. As per my understanding I cannot use @JsonBackReference here as value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration.

Can some one please advise how I can handle this scenario?

like image 587
M.Rather Avatar asked Mar 17 '11 22:03

M.Rather


2 Answers

You can use @JsonIgnoreProperties("someField") on one of the sides of the relations (the annotation is class-level). Or @JsonIgnore

like image 163
Bozho Avatar answered Sep 23 '22 01:09

Bozho


As @Bozho have answered to use @JsonIgnoreProperties, try this, it worked for me.

Below are my models with @JsonIgnoreProperties:

@Entity
public class Employee implements Serializable{
    @ManyToMany(fetch=`enter code here`FetchType.LAZY)
    @JoinTable(name="edm_emp_dept_mappg", 
        joinColumns={@JoinColumn(name="emp_id", referencedColumnName="id")},
        inverseJoinColumns={@JoinColumn(name="dept_id", referencedColumnName="id")})
    @JsonIgnoreProperties(value="employee")
    Set<Department> department = new HashSet<Department>();
}


@Entity
public class Department implements Serializable {
    @ManyToMany(fetch=FetchType.LAZY, mappedBy="department")
    @JsonIgnoreProperties(value="department")
    Set<Employee> employee = new HashSet<Employee>();
}

In value attribute of @JsonIgnoreProperties, we need to provide the collection type property of counter(related) model.

like image 39
udit khare Avatar answered Sep 23 '22 01:09

udit khare