Skip Headers

# Caching Results in a ReadQuery

Previous

Next

By default, each time you execute a `ReadQuery`, TopLink applies the current query configuration to the read operation. In doing so, TopLink will access the session cache, the data source, or both.

Some queries are known to return the same result set (for example, the number of units sold last year by the current sales person). After the first query execution, there is no need to actually execute the query if it is invoked again.

For these types of queries, you can use any TopLink `ReadQuery` and configure it to store its query results in an internal query cache.

After its first execution for a set of query parameters, the query will return its cached result set each time it is invoked with the same query parameters. This improves query performance for frequently executed queries. By default a query will cache the results sets for the last 100 queries of specific parameters. You can configure this query cache as part of the `QueryResultsCachePolicy`.

Enable this feature using `ReadQuery` method `cacheQueryResults` or by calling the `ReadQuery` method `setQueryResultsCachePolicy` with an instance of `QueryResultsCachePolicy`, and disable it using `ReadQuery` method `doNotCacheQueryResults`.

Before using this feature, consider the restrictions in "Internal Query Cache Restrictions". For more information, see "Caching Query Results in the Query Cache".

You can apply a cache invalidation policy to the query's internal cache (see "Configuring Cache Expiration at the Query Level"). For more information, see "Cache Invalidation".

Example: Configuring a ReadQuery to Cache Its Query Results shows how to configure a `ReadQuery` to cache its results.

Configuring a ReadQuery to Cache Its Query Results

    ReadObjectQuery query = new ReadObjectQuery(Employee.class);

    // Instruct the ReadQuery to cache its query results
    query.cacheQueryResults();

    // The first time you invoke it, the ReadQuery reads from the database, session
    // cache, or both and stores the result set in its internal query cache
    Employee employeeFirst = (Employee) session.executeQuery(query);

Example: Configuring a ReadQuery to Stop Caching Its Query Results shows how to configure the `ReadQuery` to stop caching its results. The next time the query is executed, TopLink does not use the query cache. Instead, the query accesses the data source.

Configuring a ReadQuery to Stop Caching Its Query Results

    // Disable query caching
    query.doNotCacheQueryResults();

    // The ReadQuery does not use the query cahce and instead accesses the database
    Employee employee = (Employee) session.executeQuery(query);

Alternativley, you can clear the query's internal cache using `ReadQuery` method `clearQueryResults` passing in your session. This clears the currently cached results and ensures that the next query execution reads from the database.