How to solve circular reference in json serializer caused by Many TO Many hibernate bidirectional mapping?
You can use @JsonIgnoreProperties("someField")
on one of the sides of the relations (the annotation is class-level). Or @JsonIgnore
As @Bozho have answered to use @JsonIgnoreProperties, try this, it worked for me.
Below are my models with @JsonIgnoreProperties:
@Entitypublic 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>();}@Entitypublic 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.
You can also use Dozer mapping to convert a POJO to a Map and exclude fields. For example if we have two classes PojoA and PojoB having bi-directional relationships, we define mapping like this
<mapping map-id="mapA" map-null="false"> <class-a>com.example.PojoA</class-a> <class-b>java.util.Map</class-b> <field> <a>fieldA</a> <b>this</b> </field> <field map-id="mapB"> <a>pojoB</a> <b>this</b> <b-hint>java.util.Map</b-hint> </field></mapping><mapping map-id="mapB" map-null="false"> <class-a>com.example.PojoB</class-a> <class-b>java.util.Map</class-b> <field-exclude> <a>pojoA</a> <b>this</b> </field-exclude></mapping>
Then you define a bean setting the above dozer mapping file as a property.
<bean id="mapper" class="org.dozer.DozerBeanMapper"> <property name="mappingFiles"> <list> <value>dozerMapping.xml</value> </list> </property></bean>
Then in the class that where you are serializing
public class TestClass{ @Autowired DozerBeanMapper mapper; public Map<String,Object> serializeObject(PojoA pojoA) { return ((Map<String, Object>) mapper.map(pojoA, Map.class, "mapA")); }}