JPA Updating Bidirectional Association

戏子无情 提交于 2019-12-28 05:54:07

问题


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);

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?


回答1:


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.

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.

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);

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.




回答2:


You have there a persist operation (made with em.merge()). Persisting a new employee does not mean that the department is also persisted (you have no cascading), so it will throw an exception because of another reason (simply try it and post the Exception).To avoid that, you either add a cascading type, or persist both of them (as you made in your example).

About your question: the only part considered would be the owning side. In the JPA 2.0 spec, Chapter 3 Entity Operations => 3.2.4 Syncrhonization to the Database is the follwoing:

Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship. It is the developer’s responsibility to keep the in-memory references held on the owning side and those held on the inverse side consistent with each other when they change. In the case of unidirectional one-to-one and one-to-many relationships, it is the developer’s responsibil- ity to insure that the semantics of the relationships are adhered to.[29]

Related to the need of a transaction: yes, you need for the merge operation an active transaction. Excerpt from JPA 2 specification:

The persist, merge, remove, and refresh methods must be invoked within a transaction con- text when an entity manager with a transaction-scoped persistence context is used. If there is no transac- tion context, the javax.persistence.TransactionRequiredException is thrown.

On how a transaction is started/how you starat a transaction: it depends on the type of the EntityManager (on the way how you get one). In EJB it is much easier to handle that for generic situations. Also, according to the documentation of the merge method, a TransactionRequiredException is thrown, if invoked on a container-managed entity manager of type PersistenceContextType.TRANSACTION and there is no transaction.



来源:https://stackoverflow.com/questions/20068742/jpa-updating-bidirectional-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!