JPA 更新双向关联 [英] JPA Updating Bidirectional Association

查看:21
本文介绍了JPA 更新双向关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下实体:

    @Entity
    public class Department {

        @OneToMany(mappedBy="department")
        private List<Employee> employees;
    }

    @Entity
    public class Employee {

        @ManyToOne
        private Department department
    }

在更新中我们需要维持双方关系如下是可以理解的:

It is understandable on an update that we need to maintain both sides of the relationship as follows:

Employee emp = new Employee();
Department dep = new Department();
emp.setDepartment(dep);
dep.getEmployees().add(emp);

到目前为止一切都很好.问题是我是否应该按如下方式在两侧应用合并,并避免使用级联进行第二次合并?

All good up till now. The question is should I apply merge on both sides as follows, and an I avoid the second merge with a cascade?

entityManager.merge(emp);
entityManager.merge(dep);

或者合并拥有方就足够了?这些合并也应该发生在事务或 EJB 中吗?或者在一个带有分离实体的简单控制器方法上做就足够了?

Or is merging the owning side enough? Also should these merges happen inside a Transaction or EJB? Or doing it on a simple controller method with detached entities is enough?

推荐答案

问题是我是否应该按如下方式在两侧应用合并,并避免使用级联进行第二次合并?

The question is should I apply merge on both sides as follows, and an I avoid the second merge with a cascade?

您可以使用级联注释元素将操作的效果传播到关联实体.级联功能最常用于父子关系.

You can use the cascade annotation element to propagate the effect of an operation to associated entities. The cascade functionality is most typically used in parent-child relationships.

merge 操作级联到由来自 Department 的关系引用的实体,如果这些关系已经用 cascade 元素值 注释了级联=MERGEcascade=ALL 注释.

The merge operation is cascaded to entities referenced by relationships from Department if these relationships have been annotated with the cascade element value cascade=MERGE or cascade=ALL annotation.

托管实体之间的双向关系将根据关系的拥有方 (Employee) 持有的引用而持久化.开发人员有责任保持拥有方 (Employee) 和反向方 (Department) 持有的内存中的引用在它们之间保持一致.改变.因此,通过以下系列语句,关系将通过单个 merge 同步到数据库:

Bidirectional relationships between managed entities will be persisted based on references held by the owning side (Employee) of the relationship. It is the developer’s responsibility to keep the in-memory references held on the owning side (Employee) and those held on the inverse side (Department) consistent with each other when they change. So, with below series of statements, the relationship will be synchronized to the database with a single merge:

Employee emp = new Employee();
Department dep = new Department();
emp.setDepartment(dep);
dep.getEmployees().add(emp);
...
entityManager.merge(dep);

这些更改将在事务提交时传播到数据库.通过使用 EntityManager#flush 方法.

These changes will be propagated to database at transaction commit. The in-memory state of the entities can be synchronized to the database at other times as well when a transaction is active by using the EntityManager#flush method.

这篇关于JPA 更新双向关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆