Skip Headers

# Schema Case 4: Choosing One out of Many

Previous

Next

In a one-to-many relationship, a single source object has a collection of other objects. In some cases, the source object frequently requires one particular object in the collection, but requires the other objects only infrequently. You can reduce the size of the returned result set in this type of case by adding an instance variable for the frequently required object. This lets you access the object without instantiating the other objects in the collection.

Table: Original Schema (Choosing One out of Many Case) represents a system by which an international shipping company tracks the location of packages in transit. When a package moves from one location to another, the system creates a new a location entry for the package in the database. The most common query against any given package is for its current location.

Original Schema (Choosing One out of Many Case)

Elements | Details | Instance Variable | Mapping | Target
--- | --- | --- | --- | ---
Title | ACME Shipping Package Location Tracking system |  |  |
Classes | Package, Location |  |  |
Tables | PACKAGE, LOCATION |  |  |
Relationships | Package | locations | one-to-many | Location

A package in this system can accumulate several location values in its LOCATION collection as it travels to its destination. Reading all locations from the database is resource intensive, especially when the only location of interest is the current location.

To resolve this type of problem, add a specific instance variable that represents the current location. You then add a one-to-one mapping for the instance variable, and use the instance variable to query for the current location. As illustrated in Table: Original Schema (Choosing One out of Many Case), because you can now query for the current location without reading all locations associated with the package, this dramatically improves the performance of the system.

Optimized Schema (Choosing One out of Many Case)

Elements | Details | Instance Variable | Mapping | Target
--- | --- | --- | --- | ---
Classes | Package, Location |  |  |
Tables | PACKAGE, LOCATION |  |  |
Relationships | Package | locations | one-to-many | Location
| Package | currentLocation | one-to-many | Location

See Also

  Schema Optimization