JPA - @OneToMany Update

Keep in mind that there are two units: Department and Employee, where there are N employees in one department.

In the department:

@OneToMany(mappedBy = "department", fetch = FetchType.EAGER)
private Collection<Employee> employees = new ArrayList<Employee>();

In Employee:

@ManyToOne(fetch = FetchType.EAGER)
private Department department;

Everything works, but I would like to add employees to the department without establishing feedback. For instance:

// I will add two employees to a department
department.getEmployees().add(employee1);
department.getEmployees().add(employee2);

// In fact, it is necessary to set the opposite side of the relationship
employee1.setDepartment(department);
employee2.setDepartment(department);

entityManager.merge(department);      
//...

So my question is: is there any way (for example, by some kind of annotation) that the JPA will understand that it should propagate the changes to the other side of the relationship without explicitly? In other words, I would only do this:

department.getEmployees().add(employee1);
department.getEmployees().add(employee2);
entityManager.merge(department);

Thank you so much!

+5
source share
3 answers

Clear answer: No, it is not possible that your JPA provider can automatically handle bidirectional relationships as you described it.

, , - :

class Department {

  public void addEmployee(Employee empl) {
    if (empl.getDepartment() != null && !this.equals(empl.getDepartment())) {
      empl.getDepartment().getEmployees().remove(empl);
    }
    empl.setDepartment(this); // use the plain setter without logic
    this.employees.add(empl);
  }
}


class Employee {
  // additional setter method with logic
  public void doSetDepartment(Department dept) {
    if (this.department != null && !this.department.equals(dept)) {
      this.department.getEmployees().remove(this);
    }
    dept.getEmployees().add(this);
    this.department = dept;
  }
}

, , , . , , , . - , .

+2

JPA Java . , , , , .

, , , , , , "" . , "mappedBy" http://www.objectdb.com/java/jpa/entity/fields , .

, , , , 15 .

+2

The only way to do this explicitly, as you mentioned.

+1
source

All Articles