Let's play with the Employer - Employee - Benefit example from the post JPA Demystified (episode 1) - @OneToMany and @ManyToOne mappings. We will use it inside the web application based on Spring Framework. Our first controller will return the employees list as the response body, in our case MappingJacksonHttpMessageConverter will be used automagically for converting the value returned by handleGet method to the response send to client.
@Controller
@RequestMapping("/employee-list.json")
public class EmployeeListController {
@Autowired
private EmployerDAO employerDAO;
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<Employee> handleGet(@RequestParam("employerId") Long employerId) {
return employerDAO.getEmployees(employerId);
}
}
When we try to fetch the data for the first time, we encounter beautiful exception: JsonMappingException: Infinite recursion (StackOverflowError) - caused by bi-directional references between the Employer - Employee - Benefit.
Looking for the possible solution, I've found a note Handle bi-directional references using declarative method(s), and after reading it, I've corrected the domain entities in following way:
@Entity
@Table(name = "EMPLOYERS")
public class Employer implements Serializable {
...
@JsonManagedReference("employer-employee")
@OneToMany(mappedBy = "employer", cascade = CascadeType.PERSIST)
public List getEmployees() {
return employees;
}
...
}
@Entity
@Table(name = "EMPLOYEES")
public class Employee implements Serializable {
...
@JsonManagedReference("employee-benefit")
@OneToMany(mappedBy = "employee", cascade = CascadeType.PERSIST)
public List getBenefits() {
return benefits;
}
@JsonBackReference("employer-employee")
@ManyToOne(optional = false)
@JoinColumn(name = "EMPLOYER_ID")
public Employer getEmployer() {
return employer;
}
...
}
@Entity
@Table(name = "BENEFITS")
public class Benefit implements Serializable {
...
@JsonBackReference("employee-benefit")
@ManyToOne(optional = false)
@JoinColumn(name = "EMPLOYEE_ID")
public Employee getEmployee() {
return employee;
}
...
}
After performing the above changes, I could finally enjoy the JSON response returned by my code:
[{"id":1, "benefits":[{"name":"Healthy Employees", "id":1, "type":"HEALTH_COVERAGE", "startDate":1104534000000, "endDate":null}, {"name":"Gold Autumn","id":2,"type":"RETIREMENT_PLAN","startDate":1104534000000,"endDate":null},{"name":"Always Secured","id":3,"type":"GROUP_TERM_LIFE","startDate":1104534000000,"endDate":null}],"firstName":"John"},{"id":2,"benefits":[],"firstName":"Mary"},{"id":3,"benefits":[],"firstName":"Eugene"}]
And as usual some links for the dessert:
superb, could you please provide sample junit test for jackson/json?
ReplyDeleteok I had a problem with junit and json but now I'm ok, thanks anyway
ReplyDeleteExcellent post. I am stuck with @ManyToMany circular relationship and looking at documentation @JsonBackReference will only work for Beans and not collections.
ReplyDeleteDo you have any thoughts on how to overcome that?
I solve my problem. Thanks :)
ReplyDeleteExcellent. Could you provide sample of controller with POST and PUT method
ReplyDeleteMy problem is that I still want the id of, using this example, the employer. I just don't want the whole object serialized. Is there a way to get the id value?
ReplyDeleteHey Maffy
DeleteDid you ever figure out how to get the id without the whole object? I'm trying to solve the same problem right now.
Thanks
Excellent, its working. Thanks alot.
ReplyDeletevard lokkur -> Could you please share your code? I'm facing a problem where in Jackson is completely ignoring the parent entity when I try to serialize the child entity.
ReplyDeleteIf you can please check out the below thread, it would help me out.
http://stackoverflow.com/questions/23869061/handling-jackson-parent-child-serialization/23869360?noredirect=1#comment36740511_23869360
Thank you.
help can
ReplyDeletethank you sir. you are life saver your code is from 2010 but we are still enjoying it.
ReplyDelete