'What Cascade type should I use to keep existing relationships on manyToMany when saving on JPA?
I'll try to make it simple:
I have an Employee and a Project entity with a many to many relationship like so:
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Cascade({})
@ManyToMany
@JoinTable(name = "employee_project_fabricio",
joinColumns = @JoinColumn(name= "employee_id"),
inverseJoinColumns = @JoinColumn(name = "project_id"))
private List<Project> projects;
}
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Cascade({})
@ManyToMany(mappedBy = "projects")
private List<Employee> employees;
Whenever I try to send a PUT request to my updateEmployee endpoint with a new list of projects, the old relationships that i already had saved gets overwriten with this new list. I want to keep the old relationships and add the new one that i just sent the request. I've tried already multiple types of cascades, but none of them seems to work.
This is my service method, just in case:
public EmployeeDTO updateEmployee(EmployeeDTO newEmployeeDTO) {
Employee employee = toEmployee(findEmployeeById(newEmployeeDTO.getId()));
List<Project> projects;
Employee employee1 = updateEmployee(employee, newEmployeeDTO);
if (newEmployeeDTO.getProjects() != null) {
projects = projectService.createProjects(newEmployeeDTO.getProjects());
employee1.setProjects(projects);
}
return toDto(employeeRepository.save(employee1));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
