1

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

3
  • In your last line you are saving an object called ‘r’... where does this ‘r’ come from? Commented May 10, 2021 at 4:36
  • Srry typo error , corrected it , but the issue still remains Commented May 10, 2021 at 6:39
  • With the latest spring version now (3.1.4), when you run the code in transaction, it would work as expected. Commented Oct 10, 2023 at 5:46

1 Answer 1

1

Naturally this happens you need to persist your new employee before adding it and saving the departments. Otherwise jpa doesn’t know anything about this employee and hence doesn’t manage it.

So please call employee = employeeRepository.save(employee) and then add it to all the departments you want.

Make sure you are adding the entity that was returned from save action - save method will return the persisted entity

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.