想象以下模型:
员工:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "employee_project", joinColumns = @JoinColumn(name = "Emp_Id"), inverseJoinColumns = @JoinColumn(name = "Proj_id"))
private Set<Project> projects = new HashSet<Project>();
项目:
@ManyToMany(mappedBy = "projects")
private Set<Employee> employees = new HashSet<Employee>();
现在,如果我创建一个引用现有项目的新员工并尝试保留该员工,我会收到错误消息:
detached entity passed to persist: Project
我按如下方式创建员工:
public void createNewEmployee(EmployeeDTO empDTO) {
Employee emp = new Employee();
// add stuff from DTO, including projects
repository.saveAndFlush(emp); // FAILS
}
我像这样更新现有的:
public void updateEmployee(EmployeeDTO empDTO) {
Employee emp = repository.findOne(empDTO.getId());
// set stuff from DTO, including projects
repository.saveAndFlush(emp); // WORKS!
}