Show TOC

Cascading Entity Manager OperationsLocate this document in the navigation structure

Use

By default, the entity manager operations affect only the entities that are directly provided as arguments to these operations. However, JPA allows cascading some or all of the entity manager operations to entities that are related to the arguments. Cascading is supported by all relationship types.

Cascading is unidirectional, that is, you must specify the cascaded operations on both sides of a relationship if you want to achieve a bidirectional behavior of the operations.

To enable cascading, you use the cascade element of the relationship annotation. By specifying the CascadeType to be PERSIST , REFRESH , MERGE or REMOVE , the corresponding operation is cascaded to all entities directly referred to by the annotated relationship. The cascade type ALL specifies cascading of all possible entity manager operations.

In a parent-child relationship, it is typical to cascade the entity manager operations from the parent entity to the child entity.

Operations that are performed on the parent object can be cascaded to the child objects, even if the parent object has not been changed.

Example

You have a department with some employees, and you add new employees to that department. In this case, you can call the PERSIST operation on the department. As a result, the new employees are persisted.

Note
  • Cascading the merge operation is convenient as it allows merging a complicated network of detached entities without knowing which of them are actually contained in the network.

  • Cascading the remove operation is recommended only for relationships of the type one-to-one and one-to-many. If there are multiple relationships pointing to the same subject entity, none of these relationships should be annotated with cascade REMOVE .

Caution

Cascading the remove operation improperly may cause unwanted deletion of entities.

Cascading a Single Operation

The following example shows how to enable cascading of a single entity manager operation:

Sample Code
                  @Entity
public class Employee {
        @Id
        private int id;
        @OneToOne(cascade=CascadeType.PERSIST)
        Address address;
}
               

Cascading Multiple Operations

The following examples show how to enable cascading of some or all of the entity manager operations:

Sample Code
                  @Entity
public class Employee {
        @Id
        private int id;
        @OneToOne(cascade={CascadeType.PERSIST, CascadeType.REMOVE})
Address address;
}
               
Sample Code
                  @Entity
public class Employee {
        @Id
        private int id;
        @OneToOne(cascade=CascadeType.ALL)
Address address;
}
               
More Information