Java Reference
In-Depth Information
In each of these cases, we will have the specific mapping from the current ResultSet row to the
WordUsage instance. This part of the implementation is the same throughout, so we will add it directly onto
our WordUsage class as a static method and reference it from there. This will allow the code samples to stay
more obviously focused on the infrastructure. This method is given in Listing 5-4. With the method in place,
we can start into our four implementations.
Listing 5-4. The WordUsage-from-ResultSet Mapping Method
/**
* Returns a new instance of this class based on the current row of a
* result set. The results within the result set are expected to be
* as follows:
* <p>
* <b>1.</b> The string title of the text<br />
* <b>2.</b> The line offset within the text<br />
* <b>3.</b> The word itself<br />
* <b>4.</b> The word offset within the line<br />
*
* @param rs The result set whose current row should be read;
* never {@code null}.
* @return A {@link WordUsage} constructed from the query results.
*/
public static WordUsage fromResultSet(ResultSet rs) throws SQLException {
Objects.requireNonNull(rs, "result set to read from");
return new WordUsage(
rs.getString(1), // title
rs.getInt(2), // line offset
rs.getString(3), // word
rs.getInt(4) // word offset
);
}
Method One: Building a Stream Using the Stream Builder
The simplest way to dynamically build a Stream is using Stream.Builder . The Stream.Builder class follows
the standard “builder” design pattern. This design pattern is an object with two phases: an accumulation
phase and a build phase. The object starts in the accumulation phase. During this phase, it takes in elements.
At some point, a trigger method is called that converts the builder into the build phase. In the build phase,
the builder is a factory, and produces instances of the desired class.
In our case, we will provide WordUsage instances into the Stream.Builder. We will do this by iterating
through the result set in the familiar way, constructing the instances, and passing them in. All of this
happens in the calling code's thread of execution, and a fully populated stream is returned to the caller.
If there is any exception in populating this stream, it is propagated directly to the caller. The code for the
Stream.Builder approach is in Listing 5-5.
 
Search WWH ::




Custom Search