Unable to save child object reference.
Employee parent object contains the child employee_detail which also has a @ManyToOne defined to save Address object.
Table structure
EMPLOYEE
ID BIGINT(20) NOT NULL AUTO_INCREMENT
NAME VARCHAR(100) NOT NULL
EMPLOYEE_DETAIL
ID BIGINT(20) NOT NULL AUTO_INCREMENT
EMPLOYEE_ID BIGINT(20) NOT NULL
ADDRESS_ID BIGINT(20) NOT NULL
Entities
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List < EmployeeDetail > employeeDetails = new ArrayList < > ();
public void addEmployeeDetail(EmployeeDetail ed) {
employeeDetails.add(ed);
ed.setEmployee(this);
}
}
@Entity
@Table(name = "employee_detail")
public class EmployeeDetail {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@ManyToOne(optional = false, cascade = CascadeType.PERSIST)
@JoinColumn(name = "employee_id")
private Employee employee;
@ManyToOne(optional = false, cascade = CascadeType.PERSIST)
@JoinColumn(name = "address_id")
private Address address;
}
In the REST Controller method:
public void saveEmployee(@RequestBody Employee employee)
{
EmployeeDetail employeeDetail = new EmployeeDetail();
employeeDetail.setEmployee(employee);
for(EmployeeDetail ed : employee.getEmployeeDetails())
{
Address address = addressService.findOne(ed.getAddress().getId());
employeeDetail.setAddress(address);
}
employee.addEmployeeDetail(employeeDetail);
//SAVE
employeeService.create(employee);
}
Exception:
nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.abc.Address
I am unable to save the Address details with the child table EmployeeDetail. What is wrong here?