OJB
Downloads
Documentation
Development
Translated (Web)
|
Using Anonymous Keys |
The Database |
When we need to store our instances in a database we use a fairly typical table per class persistance model.
 |  |  |
 |
CREATE TABLE finish
(
id INTEGER PRIMARY KEY,
wood VARCHAR(255),
color VARCHAR(255)
);
CREATE TABLE desk
(
id INTEGER PRIMARY KEY,
num_legs INTEGER,
finish_id INTEGER,
FOREIGN KEY (finish_id) REFERENCES finish(id)
);
CREATE TABLE drawer
(
id INTEGER PRIMARY KEY,
desk_id INTEGER,
FOREIGN KEY (desk_id) REFERENCES desk(id)
);
CREATE TABLE thing
(
id INTEGER PRIMARY KEY,
name VARCHAR(255),
drawer_id INTEGER,
FOREIGN KEY (drawer_id) REFERENCES drawer(id)
);
|  |
 |  |  |
At the database level the possible relationships need to be explicitely defined by teh foreign key constraints. These model all the possible object relationships according to the domain model (until generics enter the Java language for the collections API, this is technically untrue for the classes used here).
|
Benefits and Drawbacks |
There are both benefits and drawbacks to using anonymous field references for maintaining referential integrity between Java objects and database relations. The most immediate benefit is avoiding semantic code duplication. The second major benefit is avoiding cluttering class definitions with persistance mechanism artifacts. In a well layered application, the persistance mechanism will not really need to be so obvious in the object model implementation. Anonymous fields helpt o achieve this - thereby making persistence mechanisms more flexible. Moving to a different one becomes easier.
There is an indirect benefit to populating the various id type keys though, particularly in web based applications where yet another layer boundary must be crossed - to an html or html-form format where object references are again lost. If unique ids are not part of a class, they will wind up being regenerated at the object level for crossing to the next layer. While this might be a better method to a layer purist, it is considerably less efficient.
|
|
|