Java Reference
In-Depth Information
You need to carefully determine the most appropriate
cascade
setting for each
relationship on a case-by-case basis. Mostly you will want use the default
cascade
value of
none
for many-to-one and many-to-many relationships and a value of
either
all
or
all,delete-orphan
for one-to-many relationships. For example, a
value of
all,delete-orphan
is appropriate for the
Restaurant
-
MenuItem
relation-
ship because a menu item should be saved when associated with a restaurant and
deleted when either its restaurant is deleted or it is no longer associated with its
restaurant. Conversely, a value of
none
is appropriate for the
PendingOrder
-
Restaurant
relationship because the restaurant's lifecycle is independent of any
pending orders that reference it.
6.1.5
Persisting interfaces
Inheritance is an important OO concept and is widely used in domain models.
Persisting a class hierarchy is generally straightforward because Hibernate sup-
ports each of the mapping schemes described in chapter 4. It even lets you persist
interfaces, which means, for example, that you can define a mapping for the
PendingOrder
-
Coupon
relationship. However, persisting an interface is tricky if you
want the classes in the hierarchy to have an identifier property. Unlike a class,
which can define private accessors for the identifier property or a private identi-
fier and a public getter, an interface must define public accessors, which is not a
desirable approach because of the lack of encapsulation.
For example, if we want the classes in the
Coupon
hierarchy to have an identifier
property the
Coupon
interface must define a
getId()
and a
setId()
method:
public interface Coupon {
int getId();
void setId(int id);
…
}
Any of the
Coupon
's clients could call the
getId()
and
setId()
methods, which is
less than ideal. Moreover, the classes that implement this interface are required to
define accessors, which is extra code that must be written.
One way to improve encapsulation is to insert an abstract class into the hierar-
chy that implements the interface and defines the
id
field. The other classes in the
hierarchy are changed to extend the abstract class. The
O/R
mapping persists this
class instead of the interface. Although you do not need to change the type of any
of the fields that reference the interface, their association mapping elements must
have a
class
attribute that defines the property type to be the abstract class. This is
Search WWH ::
Custom Search