Skip Headers

# Determining Whether or Not an Object Is the Cache Object

Previous

Next

In "Modifying an Object", it was noted that it is possible to read any particular instance of a class by executing:

    session.readObject(Class);

There is also a `readObject` method that takes an object as an argument: this method is equivalent to doing a `ReadObjectQuery` on the primary key of the object passed in. For example, the following code is equivalent to the code in the subsequent example:

    session.readObject(pet);

The following is equivalent to the preceding code:

    ReadObjectQuery query = new ReadObjectQuery();
    query.setReferenceClass(Pet.class);
    ExpressionBuilder builder = new ExpressionBuilder();
    Expression exp = builder.get("id").equal(pet.getId());
    query.setSelectionCriteria(exp);
    session.executeQuery(query);

Also note that primary key-based queries, by default, will return what is in the cache without going to the database. As a result, you can use very quick and simple method for accessing the cache copy of an object as shown in Example: Testing If an Object Is the Cache Object.

Testing If an Object Is the Cache Object

    //Here is a test to see if an object is the cache copy
    boolean cached = CACHE_PET == session.readObject(CACHE_PET);
    boolean cloned = CLONE_PET == session.readObject(CLONE_PET);
    System.out.println("Is CACHE_PET the Cache copy of the object: " + cached);
    System.out.println("Is CLONE_PET the Cache copy of the object: " + cloned);

This code produces the following output:

    Is CACHE_PET the Cache copy of the object: true
    Is CLONE_PET the Cache copy of the object: false