Reputation: 561
I am building an application with spring boot and have to setup a self-referencing relationship.
In order to make the scenario simple and easy to understand, I have tried to work on a similar scenario with a department entity example.
Following is the scenario for which I need to setup a self-referencing relationship
To setup such a scenario, I have defined the entity Department in the following way.
Department.java
public class Department {
@Id
@GenericGenerator(name = "sequence_department_id", strategy = "com.app.mycompany.AgileCenterServices.util.DepartmentIdGenerator")
@GeneratedValue(generator = "sequence_department_id")
@Column(unique = true)
private String id;
private String name;
private String location;
private String costCenter;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="parentDepartment")
private Department parentDepartment;
@OneToMany(mappedBy="parentDepartment")
private Set<Department> linkedDepartments = new HashSet<Department>();
/* getters & setters */
}
DepartmentController.java
@CrossOrigin
@RequestMapping(value = "/", method = RequestMethod.POST)
public Department createDepartment(@RequestBody String trial) throws Exception {
logger.info("Inside createDepartment() API ");
ObjectMapper objmapper = new ObjectMapper();
ObjectNode node = objmapper.readValue(trial, ObjectNode.class);
Department deptInput = objmapper.convertValue(node, Department.class);
Department deptRec = null;
/* check if parent department information was passed */
if(deptInput.getParentDepartment() != null) {
Department parentDepartment = departmentRepository.findOne(deptInput.getParentDepartment().getId());
deptInput.setParentDepartment(parentDepartment);
}
try {
logger.info("createDepartment() :: Before save :: Input data ::: " + deptInput.toString());
deptRec = departmentRepository.save(deptInput);
logger.info("createDepartment() :: After save :: Saved successfully ::: " + deptRec.toString());
}
catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
logger.info("Leaving createDepartment() API");
return deptRec;
}
For now, I have just tried linking the department to another parentDepartment as shown in the above example and tried to create the department using spring boot-REST service
The departments are getting created appropriately.
Saved Department 1 with following input
{"name":"Sales", "costCenter": "SLS", "location":"Global"}
Output:
{
"id": "1000",
"name": "Sales",
"location": "Global",
"costCenter": "SLS",
"parentDepartment": null,
"linkedDepartments": []
}
Saved department 2 with following input
{"name":"Sales-IN", "costCenter": "SLS-IN", "location":"India", "parentDepartment":{"id":"1000"}}
Output:
{
"id": "1001",
"name": "Sales-IN",
"location": "India",
"costCenter": "SLS-IN",
"parentDepartment": {
"id": "1000",
"name": "Sales",
"location": "Global",
"costCenter": "SLS",
"parentDepartment": null,
"linkedDepartments": []
},
"linkedDepartments": []
}
However, when I use postman to now query the data in departments, i notice the following exception
@CrossOrigin
@RequestMapping(value="/", method = RequestMethod.GET)
public Page<Department> listDepartments(Pageable pageable) {
logger.info("Inside listDepartments() API");
return departmentRepository.findAll(pageable);
}
Exception
2019-03-06 20:04:12.190 WARN 19520 --- [io-8080-exec-10] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.app.mycompany.AgileCenterServices.entities.Department["linkedDepartments"]->org.hibernate.collection.internal.PersistentSet[0]->com.app.mycompany.AgileCenterServices.entities.Department["parentDepartment"]->com.app.mycompany.AgileCenterServices.entities.Department["linkedDepartments"]->org.hibernate.collection.internal.PersistentSet[0]->com.app.mycompany.AgileCenterServices.entities.Department["parentDepartment"]->com.app.mycompany.AgileCenterServices.entities.Department["linkedDepartments"]
To fix the above issue, I set @JsonBackReference on the "linkedDepartments" attribute after which the "GET" operation works properly. but the save operation now fails with
2019-03-06 20:19:03.176 WARN 19520 --- [nio-8080-exec-3] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.StackOverflowError
What am i doing wrong here?
Upvotes: 4
Views: 12214
Reputation: 434
I tried your code and as long as you have @JsonBackReference on linkedDepartments or parentDepartment, it won't be serialized, which resolves infinite recursion. The save method also works fine. I can post code to GitHub for you reference. Let me know.
Upvotes: 6