Java Reference
In-Depth Information
private static final int CHARACTERISTICS =
Spliterator.IMMUTABLE | Spliterator.DISTINCT | Spliterator.NONNULL;
private final ResultSet resultSet;
/**
* Constructor.
*
* @param resultSet The result set to process; may not be {@code null}.
* @param additionalCharacteristics Relevant characteristics beyond
{@link java.util.Spliterator#IMMUTABLE}
* and {@link java.util.Spliterator#NONNULL},
* or {@code 0} if none
*/
public ResultSetSpliterator(
final ResultSet resultSet,
final int additionalCharacteristics
) {
super(Long.MAX_VALUE, CHARACTERISTICS | additionalCharacteristics);
Objects.requireNonNull(resultSet, "result set");
this.resultSet = resultSet;
}
// See Listing 5-9 for more code that goes here
}
There is just one problem left to solve: closing the ResultSet. If the user passes the ResultSet into this
object, and then closes the ResultSet, this spliterator may not have been called. We saw this issue before in
streams, and we used the onClose callback to handle it. Unlike streams, spliterators do not have a concept of
being closed, so we will have to build it ourselves. What we would like is for the ResultSet to be closed when
we finish working our way through it. The ResultSet might also be holding up a Statement or a Connection,
too, and so we would like to give the user the option to close those, as well. To support this, our constructor
will take a variable number of AutoCloseable instances, and we will close them whenever we exhaust
the result set. This involves adding a doClose() method and a call to that method when the ResultSet is
exhausted. The result of updating our class is in Listing 5-11.
Listing 5-11. Completed ResultSetSpliterator Class
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.*;
/**
* A {@link java.util.Spliterator} that traverses a {@link java.sql.ResultSet}.
* When the result set is exhausted, it will be automatically closed.
* Implementing classes must extend {@link #processRow(java.sql.ResultSet)} to
* specify how to convert a row into a result object.
*/
public abstract class ResultSetSpliterator<RESULT_T>
extends Spliterators.AbstractSpliterator<RESULT_T>
{
 
Search WWH ::




Custom Search