Created
February 28, 2019 00:57
-
-
Save flying3615/25013373db3f0e5dcefeb3469b962677 to your computer and use it in GitHub Desktop.
Generate resultset stream for getting all customers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @return a lazily populated stream of customers. Note the stream returned must be closed to | |
* free all the acquired resources. The stream keeps an open connection to the database till | |
* it is complete or is closed manually. | |
*/ | |
@Override | |
public Stream<Customer> getAll() throws Exception { | |
Connection connection; | |
try { | |
connection = getConnection(); | |
PreparedStatement statement = connection.prepareStatement("SELECT * FROM CUSTOMERS"); // NOSONAR | |
ResultSet resultSet = statement.executeQuery(); // NOSONAR | |
return StreamSupport.stream(new Spliterators.AbstractSpliterator<Customer>(Long.MAX_VALUE, | |
Spliterator.ORDERED) { | |
@Override | |
public boolean tryAdvance(Consumer<? super Customer> action) { | |
try { | |
if (!resultSet.next()) { | |
return false; | |
} | |
action.accept(createCustomer(resultSet)); | |
return true; | |
} catch (SQLException e) { | |
throw new RuntimeException(e); // NOSONAR | |
} | |
} | |
}, false).onClose(() -> mutedClose(connection, statement, resultSet)); | |
} catch (SQLException e) { | |
throw new CustomException(e.getMessage(), e); | |
} | |
} | |
private Connection getConnection() throws SQLException { | |
return dataSource.getConnection(); | |
} | |
private void mutedClose(Connection connection, PreparedStatement statement, ResultSet resultSet) { | |
try { | |
resultSet.close(); | |
statement.close(); | |
connection.close(); | |
} catch (SQLException e) { | |
LOGGER.info("Exception thrown " + e.getMessage()); | |
} | |
} | |
private Customer createCustomer(ResultSet resultSet) throws SQLException { | |
return new Customer(resultSet.getInt("ID"), | |
resultSet.getString("FNAME"), | |
resultSet.getString("LNAME")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment