Datasheet
newFeatures and count columns need to be populated with a value such as null. But will this work?
Can’t we have a SpecialEditionCD object where both the count and newFeatures attributes are null? In
that case, how can we tell which object has been stored? We add to the database schema an addition field
called type that the mapping software uses to keep track of the class type to which a particular row
belongs.
As you can see from this example, adding new classes to the class model as well as the database is as
simple as adding columns to the single hierarchy table. There is complete support for polymorphism
because of the type column. Changing the type value from one class to another changes the object class
type. We don’t need to keep track of additional tables since all the information for the class hierarchy can
be found in the single table.
If you have a large hierarchy, the single-table option isn’t ideal because of the potential for wasted space
from row to row. If an object is higher in the hierarchy, there will be quite a few nulled column values.
Further, the database may potentially have a large number of columns. This isn’t usually a problem for
database-management software, but the database can be difficult to read and maintain.
Table-Per-Class Inheritance Mapping
If you want to eliminate some of the issues with the single-table approach to mapping an inheritance
hierarchy, consider creating a single table for each of the classes. Figure 1.4 shows an example of the
object-to-table mapping.
Figure 1.4
In Figure 1.4, we’ve created three tables to handle the CD inheritance hierarchy. The CD and cd_tracks
tables monitor the attribute needed for a CD object. For the SpecialEditionCD class, we create another
table to hold the information new to this class. If the object we’re mapping to the database is a CD class,
then we just need to access the two base tables. However, if we have a SpecialEditionCD, we need to
access three tables to pull out all the information needed to save or load the object from the database. If
the persistence layer is intelligent, we won’t necessarily hit all three tables for a SpecialEditionCD—only
the tables needed at a particular moment.
If we add more classes to the hierarchy, we need to build the appropriate database table to fulfill the nec-
essary mappings. Various relationship must be maintained between the rows for each subchild object
SpecialEditionCD
ID : int
newFeatures : varchar(256)
count : int
CD
ID : int
type : varchar(256)
title : varchar(256)
artist : varchar(256)
cd_tracks
ID : int
cd_id : int
name : varchar(256)
length : int
10
Chapter 1
03_576771_c01.qxd 9/1/04 12:09 PM Page 10










