如何在Spring JPA中保存引用现有实体的新实体?
2022-09-03 13:55:41
想象一下以下模型:
员工:
@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!
}