Java Reference
In-Depth Information
CASCADING OPERATIONS
When an association between two entities is established (for example, a one-to-one association between
Human and Pet ), it is common to want certain persistence operations on one entity to also be applied to the
entity that it is linked to. Take, for example, the following code:
Human dave = new Human("dave");
Pet cat = new PetCat("Tibbles");
dave.setPet(cat);
session.save(dave);
In the last line, highlighted in bold, we are likely to want to save the Pet object associated with the
Human object. In a one-to-one relationship, we usually expect all operations on the owning entity to be prop-
agated through—that is, to be cascaded —to the dependent entity. In other associations this is not true, and
even in a one-to-one relationship we may have special reasons for wanting to spare the dependent entity
from delete operations (perhaps for auditing reasons).
We are therefore able to specify the types of operations that should be cascaded through an association
to another entity using the cascade annotation, which takes an array of members of the CascadeType enu-
meration. The members correspond with the names of the key methods of the EntityManager class used
for EJB 3 persistence, and have the following rough correspondence with operations on entities:
ALL requires all operations to be cascaded to dependent entities. This is the same as including MERGE ,
PERSIST , REFRESH , and REMOVE .
MERGE cascades updates to the entity's state in the database (i.e., UPDATE ...).
PERSIST cascades the initial storing of the entity's state in the database (i.e., INSERT ...).
REFRESH cascades the updating of the entity's state from the database (i.e., SELECT ...).
REMOVE cascades deletion of the entity from the database (i.e., DELETE . . .).
If no cascade type is specified, no operations will be cascaded through the association.
In the light of these options, the appropriate annotation for the relationship between a publisher and its
address would be as follows:
@OneToOne(cascade=CascadeType.ALL)
public Address getAddress() {
return this.address;
}
The simplest way to maintain a many-to-one relationship between two entities is by
managing the foreign key of the entity at the “one” end of the one-to-many relationship as a
column in the “many” entity's table.
The @OneToMany annotation can be applied to a field or property value for a collection or
an array representing the mapped “many” end of the association.
Search WWH ::




Custom Search