Skip Headers

# Reading an Object With a Session Query

Previous

Next

The `readObject` method retrieves a single object from the database. The application must specify the class of object to read. If no object matches the criteria, a null value is returned.

For example, the basic read operation is:

    session.readObject(MyDomainObject.class);

This example returns the first instance of `MyDomainObject` found in the table used for `MyDomainObject`. TopLink provides the `Expression` class to specify querying parameters for a specific object.

When you search for a single, specific object using a primary key, the `readObject` method is more efficient than the `readAllObjects` method, because `readObject` can find an instance in the cache without accessing database. Because a `readAllObjects` method does not know how many objects match the criteria, it always searches the database to find matching objects, even if it finds matching objects in the cache.

readObject Using an Expression

    import oracle.toplink.sessions.*;
    import oracle.toplink.expressions.*;

    /* Use an expression to read in the employee whose last name is Smith. Create an expression using the Expression Builder and use it as the selection criterion of the search */
    Employee employee = (Employee) session.readObject(Employee.class, new ExpressionBuilder().get("lastName").equal("Smith"));