Datasheet

Primary Keys, Timestamps, and Version Numbers
In the examples presented so far, all the database tables have included a primary key that isn’t part of
the original object being mapped. The primary key is needed in order for the database server to uniquely
distinguish and manage the objects stored in the database. Without the primary key, the database might
have duplicate rows in a table because two objects in the system have identical attribute values. The pri-
mary key also gives us the ability to determine whether or not an object has actually been added to the
database and if the object needs to be updated.
Depending on the system used to handle the mapping from objects to permanent storage, there are dif-
ferent ways to determine whether an object is up to date. One way is to use a timestamp in the database
table. When the persistence layer needs to determine whether an object should be persisted to the
database, it can check the timestamp in the table row for the object. If the timestamp is less than a time-
stamp kept in the object itself, the persistence layer knows the object should be persisted. If the time-
stamps are the same, the object hasn’t been changed and doesn’t need to be saved.
Another technique involves a version number stored in the database. When the object is pulled from the
database, it has an associated version number. If the application changes the object in any way, the per-
sistence layer updates the version number by a single digit. The layer can then use the version number
to determine whether the object needs to be persisted.
Handling Inheritance
Obtaining efficiencies in the software development process means using all of a methodology’s features.
This is especially true when you’re developing the classes for an application. During the development of
the class structure, a clear hierarchy can sometimes be created through inheritance. For example, for our
CD class, we might have another class called SpecialEditionCD that inherits its foundational attributes
from the CD class:
public class SpecialEditionCD extends CD {
String newFeatures;
int cdCount;
public SpecialEditionCD(
String title,
String artist,
String newFeatures,
int cdCount) {
this.title = title;
this.artist = artist;
this.newFeatures = newFeatures;
this.cdCount = cdCount;
}
}
The SpecialEditionCD class adds two more attributes that need to be persistent to our permanent stor-
age in addition to the attributes from the CD parent class. We can’t easily store the SpecialEditionCD
information in the CD database table because of these new attributes. How do we perform the mapping?
There are several solutions:
8
Chapter 1
03_576771_c01.qxd 9/1/04 12:09 PM Page 8