假设我们有以下实体:
@Entity
public class Department {
@OneToMany(mappedBy="department")
private List<Employee> employees;
}
@Entity
public class Employee {
@ManyToOne
private Department department
}
可以理解的是,我们需要维护双方的关系,如下所示:
Employee emp = new Employee();
Department dep = new Department();
emp.setDepartment(dep);
dep.getEmployees().add(emp);
到目前为止一切都很好。问题是我是否应该按如下方式在两侧应用合并,并且避免使用级联进行第二次合并?
entityManager.merge(emp);
entityManager.merge(dep);
或者合并拥有方就足够了吗?这些合并还应该发生在事务或 EJB 中吗?或者在具有分离实体的简单 Controller 方法上执行此操作就足够了吗?
最佳答案
The question is should I apply merge on both sides as follows, and an I avoid the second merge with a cascade?
您可以使用级联注释元素将操作的效果传播到关联的实体。级联功能最常用于父子关系。
merge
操作级联到由 Department
中的关系引用的实体,如果这些关系已用 cascade
元素值 注释cascade=MERGE
或 cascade=ALL
注释。
托管实体之间的双向关系将根据关系的拥有方 (Employee)
持有的引用进行持久化。开发人员有责任使拥有方 (Employee)
和相反方 (Department)
持有的内存中引用在它们时彼此保持一致改变。因此,通过以下一系列语句,关系将通过单个 merge
同步到数据库:
Employee emp = new Employee();
Department dep = new Department();
emp.setDepartment(dep);
dep.getEmployees().add(emp);
...
entityManager.merge(dep);
这些更改将在事务提交时传播到数据库。通过使用 EntityManager#flush,实体的内存状态可以在其他时间同步到数据库,也可以在事务处于 Activity 状态时同步。方法。
关于java - JPA 更新双向关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20068742/