I have two entities that are related by many to many relationship. Now I have a new record created and I need to update the relationship but while doing so I am getting duplicate entry per parent record in one of the child table. below are the entity code
@Entity
@Table(name = "Employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
@ManyToMany(fetch = FetchType.EAGER,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "employees")
private Set<Department> departments = new HashSet<>();
public Employee() {
}
public Employee(String title) {
this.title= title;
}
public Integer getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Set<Department> getDepartments() {
return departments;
}
public void setDepartments(Set<Department> departments) {
this.departments = departments;
}
@Override
public String toString() {
return "Colmn [id=" + id + ", title=" + title + "]";
}
}
@Entity
@Table(name = "Department")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String company;
@ManyToMany(fetch = FetchType.EAGER,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@Fetch(FetchMode.JOIN)
@JoinTable(name = "dept_emp",
joinColumns = { @JoinColumn(name = "dept_id") },
inverseJoinColumns = { @JoinColumn(name = "emp_id") })
private Set<Employee> employees = new HashSet<>();
public Department() {
}
public Department(String company) {
this.company = company;
}
public long getId() {
return id;
}
public String getCompany() {
return company;
}
public void setCompany(long company) {
this.company = company;
}
public Set<Employee> getEmployees() {
return employees;
}
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
@Override
public String toString() {
return "Department [id=" + id + ", company=" + company + ", employees=" + employees + "]";
}
}
I am using spring curd repository
public interface DepartmentRepository extends CrudRepository<Department, Long> {
}
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
}
Now I have existing records in the database I want to add a new employee to the system who belong to all the departments , so I did below
/**Search all the existing departments*/
List<Department> depts = (List<Department>) departmentRepository.findAll();
/**Create the new employee record*/
Employee employee = new Employee();
employee.setTitle("Adam");
/**Iterate and create the relatonship*/
for (Department d : depts) {
d.getEmployees().add(employee);
employee.getDepartments().add(d);
departmentRepository.save(d);
}
The issue is for every department I am having one record inserted in the employee table , i.e if I have 5 department then I am having 5 times employee record i.e "Adam" inserted in the employee table. Department table is not having any issue.
How to handle this