Skip Headers

# Cursored Stream Support

Previous

Next

Cursored streams combine the iterative ability of the `ScrollableCursor` interface with TopLink support for streams. The result is the ability to read back a query result set from the database in manageable subsets, and to scroll through the result set stream.

The `useCursoredStream` method of the `ReadAllQuery` class provides cursored stream support.

Cursored Streams

    CursoredStream stream;
    ReadAllQuery query = new ReadAllQuery(Employee.class);
    query.useCursoredStream();
    stream = (CursoredStream) session.executeQuery(query);

The query returns an instance of `CursoredStream` rather than a `Vector`, which can be a more efficient approach. For example, consider the following two code examples. Example: Using a Vector returns a `Vector` that contains all employee objects. If ACME has 10,000 employees, the `Vector` contains references to 10,000 `Employee` objects.

Using a Vector

    ReadAllQuery query = new ReadAllQuery(Employee.class);
    Enumeration employeeEnumeration;

    Vector employees = (Vector) session.executeQuery(query);
    employeeEnumeration = employee.elements();

    while (employeeEnumeration.hasMoreElements())
    {
    Employee employee = (Employee) employeeEnumeration.nextElement();
    employee.doSomeWork();
    }

The following example returns a `CursoredStream` instance rather than a `Vector`. The `CursoredStream` collection appears to contain all 10,000 objects, but initially contains a reference to only the first 10 `Employee` objects. It retrieves the remaining objects in the collection as they are needed. In many cases, the application never needs to read all the objects:

    ReadAllQuery query = new ReadAllQuery(Employee.class);
    query.useCursoredStream();

    CursoredStream stream = (CursoredStream) session.executeQuery(query);
    while (! stream.atEnd()) {
        Employee employee = (Employee) stream.read();
        employee.doSomeWork();
        stream.releasePrevious();
    }
    stream.close();

Note: The `releasePrevious` message is optional. This releases any previously read objects and frees system memory. Even though released objects are removed from the cursored stream storage, they remain in the identity map.