Wednesday, 18 December 2013

Cascading in JPA

To begin, let’s consider the changes required to make the persist()operation cascade from Employee
to Address. In the definition of the Employeeclass, there is a @ManyToOne annotation defined for the
address relationship. To enable the cascade, we must add the PERSISToperation to the list of cascading
operations for this relationship of the Employee entity that
demonstrates this change.
.Enabling Cascade Persist
public class Employee {
// ...
Address address;
// ...
To leverage this change, we need only ensure that the Add ressentity has been set on the Employee
instance before invoking persist()on it. As the entity manager encounters the Employee instance and
adds it to the persistence context, it will navigate across the address relationship looking for a new
Address entity to manage as well. In comparison with the approach in Listing
Cascade settings are unidirectional. This means that they must be explicitly set on both sides of a
relationship if the same behavior is intended for both situations. For example, in Listing, we only
added the cascade setting to the address relationship in the Employee entity. If Listing were
changed to persist only the Address entity, not the Employee entity, the Employee entity would not
become managed because the entity manager has not been instructed to navigate out from any
relationships defined on the Address entity.
Share it Please


Post a Comment

Copyright @ 2013 Learn About Computers and Programming. Designed by Templateism | Love for The Globe Press