PriDE Design Patterns: Caching


A strong measure to speed up persistent data access is the introduction of a cache for repeatedly queried entities. The only basic requirement is a unique identification of all entities of interest as it is defined by primary key or at least unique constraints in the database. PriDE does not provide any caching functionality by itself, so the following explainations must be understood as general remarks on that issue.

As mentioned already in the patterns for separation of database and business concerns, it is generally recommended for larger applications to follow a layered architectural model. By definition of a persistence layer, the database access can be encapsulated in the implementation of storage facades or data access objects. For the well-known class Customer this may look like this:
 
class CustomerStore {

    void createCustomer(Customer customer) throws SQLException {
        customer.create();
    }

    Customer getCustomer(int id) throws SQLException {
        return new Customer(id);
    }

    // and so forth
}

Under this precondition, the implementation can easily by extended by caching functionality as it is demonstrated in the most simple form in the following example:
 
class CustomerStore {
    private Map customers = new HashMap();
    
    void createCustomer(Customer customer) throws SQLException {
        customer.create();
        customers.put(new Integer(customer.getId()), customer);
    }
    
    Customer getCustomer(int id) throws SQLException {
        Customer c = (Customer)customers.get(new Integer(id));
        if (c == null) {
            c = new Customer(id);
            customers.put(new Integer(id), c);
        }
        return c;
    }

    // and so forth
}

On introduction of caching functionality there are some important issues to be kept in mind, which make this feature not as generally reasonable as it is sold in many commercial O/R mapping toolkits:

The source code of the example above is available under examples/caching.


Home Introduction Javadoc