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

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

问题描述

假设我们有以下实体:

Lets assume we have the following Entities:

    @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 操作级联到由如果这些关系已用级联元素值 cascade = MERGE <部门 / code>或 cascade = 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天全站免登陆