Java Reference
In-Depth Information
when the application creates a restaurant and its menu items, Hibernate must
update the database. Similarly, when the application wants to delete a restaurant
and its menu items, it must call Hibernate to delete them from the database. Sim-
ply using the
new
operator to create an object or relying on the garbage collector
to delete an object is insufficient.
Hibernate provides a couple of ways of doing this. One option is for an appli-
cation to explicitly call
save()
to save a persistent object and
delete()
to delete a
persistent object. We would, for example, call
save()
or
delete()
on the restau-
rant and each of its menu items. The other option is to configure Hibernate to
automatically persist an object when it is referenced by an already persistent
object and delete an object when either its referencing object is deleted or it
becomes unassociated from its parent object. We can, for example, configure
Hibernate to automatically save the restaurant's menu items when the restaurant
is saved and to delete the menu items when the restaurant is deleted. Not only
does automatically invoking operations such as save and delete on related objects
preserve the consistency of the database, but it also means that you have to write a
lot less code.
You can control what happens on a per-relationship basis by specifying a value
for the
cascade
attribute of an association-mapping element, which describes how
the relationship is mapped to the database schema. The
cascade
attribute is a
comma-separated list of values that correspond to the names of certain
Session
methods. It specifies whether a method that is invoked on the parent object
should recursively propagate to the child objects. For example, a value of
save-
update
specifies that
save()
should also save the children, and a value of
delete
specifies that
delete()
should delete the children. The possible values for the
cascade
attribute include:
■
none
: The application must explicitly save or delete the referenced object
and is the default value unless overridden by the
default-cascade
attribute
of the
<hibernate-mapping>
element.
■
save-update
: Hibernate will automatically save the referenced object when
it is associated with a referencing object that is already persistent or when
the referencing object is saved.
■
all
: Hibernate will automatically save and delete the referenced object with
the referencing object.
■
delete
: Hibernate will delete the children when the parent is deleted.
delete-orphan
: This value is used for collections and specifies that an object
is automatically deleted when it is removed from the collection.
■
Search WWH ::
Custom Search