I have 2 Entities, Hospital and Department, Department reference its hospital by hospital_id in it.
@Entity
public class Hospital {
...
private Set<Department> departments;
@OneToMany(mappedBy = "hospital", cascade = CascadeType.ALL)
public Set<Department> getDepartments() {
return departments;
}
}
@Entity
public class Department {
...
private Hospital hospital;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "hospital_id")
public Hospital getHospital() {
return hospital;
}
}
I use Rest API to create instance of Entities:
@RequestMapping("/create")
@ResponseBody Hospital create(@RequestBody Hospital hospital){
hospital = hospitalService.save(hospital);
return hospital;
}
I post json payload to create a Hospital:
{"name":"t-hospital", "departments":[{"name": "department1"}]}
Since I use SpringBoot, Jackson will auto parse the json payload into Java Object, here its Hospital and Departments in it.
While after I save the hospital, I found the foreign key: 'hospital_id' in department is not set.
Why is this and if possible, how can I make the foreign key set when I save the hospital object?