Java Reference
In-Depth Information
Cascading remove operations
Just as with merging and persisting entities, you must set the cascade element of a relation-
ship annotation to either
ALL
or
REMOVE
for related entities to be removed with the one
passed to the
remove
method. For example, you can specify that the
BillingInfo
en-
tity related to a
Bidder
be removed with the owning
Bidder
entity as follows:
@Entity
public class Bidder {
@OneToOne(cascade=CascadeType.REMOVE)
public BillingInfo setBillingInfo() {
From a common usage perspective, this setup makes perfect sense. There's no reason for
a
BillingInfo
entity to hang around if the enclosing
Bidder
entity it's related to is
removed. When it comes down to it, the business domain determines if deletes should be
cascaded. In general, you might find that the only relationship types where cascading re-
moval makes sense are one-to-one and one-to-many. You should be careful when using the
cascade delete because the related entity you're cascading the
delete
to may be related to
other entities you don't know about. For example, assume there's a one-to-many relation-
ship between the
Seller
and
Item
entities and you're using cascade delete to remove a
Seller
and its related
Items
. Remember the fact that other entities such as
Category
also hold references to the
Items
you're deleting, and those relationships would become
meaningless!
Handling relationships
If your intent was really to cascade-delete the
Item
s associated with the
Seller
, you
should iterate over all instances of
Category
that reference the deleted
Item
s and re-
move the relationships first, as follows:
List<Category> categories = getAllCategories();
List<Item> items = seller.getItems();
for (Item item: items) {
for (Category category: categories) {
category.getItems().remove(item);
}
}
entityManager.remove(seller);