Skip Headers

# Primary Key Queries and the Cache

Previous

Next

When a query searches for a single object by a primary key, TopLink extracts the primary key from the query and attempts to return the object from the cache without accessing the database. If the object is not in the cache, the query executes against the database, builds the resulting object(s), and places it in the identity map.

If the query is based on a nonprimary key selection criteria or is a read-all query, the query executes against the database (unless you are using `ReadObjectQuery` or `ReadAllQuery` method `checkCacheOnly`). The query matches primary keys from the result set to objects in the cache, and returns the cached objects, if any, in the result set.

If an object is not in the cache, TopLink builds the object. If the query is a refreshing query, TopLink updates the contents of any objects with the results from the query. Use "equals" on the object identity to properly configure and use an identity map.

Clients can refresh objects when they want to ensure that they have the latest data at a particular time.

Traversing Relationships With Compound Primary Keys

When getting objects by using compound primary keys to traverse relationships, you must create use query keys (see "Query Keys and Expressions"). By adding a query key for each mapped attribute in a class with a complex primary key, TopLink can use the primary key on the cache.

Consider the class `MyClass` with two attributes: `A` and `B`. Both `A` and `B` are mapped as 1:1 mappings to the database and designated primary keys.

You should create a query key for each attribute (such as `MyQueryKeyA` and `MyQueryKeyB`) that will map the attributes of the primary key of MyClass without going through the other classes. You can then use the query key to find the object in the cache and query the object's primary key:

    builder.get("MyQueryKeyA").equal(new Long("123456"));