findIterate (Execute a query iterating over the results)

Execute the query iterating over the results. This is good for processing large results where we want to avoid holding all the beans/results in memory but instead iterator through them.

Note that findIterate (and findEach and findEachWhile) uses a "per graph" persistence context scope and adjusts jdbc fetch buffer size for large queries. As such it is better to use findList for small queries.

Remember that with QueryIterator you must call close() when you have finished iterating the results (typically in a finally block).

findEach() and findEachWhile() are preferred to findIterate as they ensure the jdbc statement and resultSet are closed at the end of the iteration.

This query will execute against the Database that was used to create it.

Closing Resources

As stated before, we must ensure the iterator is closed as it holds JDBC resources. We should use try-with-resources or a try-finally block to make sure that the QueryIterator is closed regardless of exceptions thrown during processing. Note that findEach and findEachWhile ensure all resources are closed regardless and for this reason they are recommended over findIterate. There are some use cases where findEach and findEachWhile don't naturally fit and that is when we would look to use findIterate.

Example Code

Example with try-finally
Query<Customer> query = database.find(Customer.class)
   .where().eq("status", Status.NEW)
   .order().asc("id");

QueryIterator<Customer> it = query.findIterate();
try {
  while (it.hasNext()) {
    Customer customer = it.next();
    // do something with customer ...
  }
} finally {
  // close the underlying resources
  it.close();
}

 
Example with try-with-resources
try (QueryIterator<Customer> it = query.findIterate()) {
   while (it.hasNext()) {
     Customer customer = it.next();
     customer.getName();
     count.incrementAndGet();
   }
}