We are getting JSON data from front end to Spring REST controller in the below format,
{
"employerName":"ABC Corp",
"employees":[
{"employeeName":"Rambo"},
{"employeeName":"Mark"},
{"employeeName":"Jaicey"},
{"employeeName":"John"}
]
}
We have figured out two solutions to map the one-to-many relationship between employer and employee
Solution: 1 (Owner as one side)
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "employer_id")
private Set<Employee> employees = new HashSet<Employee>();
@ManyToOne
@JoinColumn(name = "employer_id")
private Employer employer;
Solution: 2 (Owner as many side)
@OneToMany(mappedBy = "employer", cascade = CascadeType.ALL)
private Set<Employee> employees = new HashSet<Employee>();
@ManyToOne
@JoinColumn(name = "employer_id")
private Employer employer;
Now the problem is that first approach fires additional update statements and has been declared unoptimised as per hibernate docs.
The second approach required iteration over employees list and setting value of employer for each employee in rest controller
Please help with the optimised approach to solve / configure the mapping.