Skip to content

Instantly share code, notes, and snippets.

@bademux
Created January 30, 2021 11:40
Show Gist options
  • Save bademux/2f438d93bbc6185975555de740a2677f to your computer and use it in GitHub Desktop.
Save bademux/2f438d93bbc6185975555de740a2677f to your computer and use it in GitHub Desktop.
Jdbs with java streams pos
package pl.com.tiger.httpaccess.messageManager;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Spliterator;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static java.lang.Long.MAX_VALUE;
@Slf4j
@UtilityClass
public class JdbcStream {
@SneakyThrows
public static Stream<ResultSet> of(Callable<Connection> collectionFactory, String sql) throws SQLException {
return of(collectionFactory.call(), sql);
}
public static Stream<ResultSet> of(Connection conn, String sql) throws SQLException {
try {
return of(conn.prepareStatement(sql)).onClose(() -> safeClose(conn));
} catch (SQLException e) {
safeClose(conn);
log.debug("Error while on sql request {}", sql, e);
throw e;
}
}
public static Stream<ResultSet> of(PreparedStatement stmt) throws SQLException {
try {
return of(stmt.executeQuery()).onClose(() -> safeClose(stmt));
} catch (SQLException e) {
safeClose(stmt);
throw e;
}
}
public static Stream<ResultSet> of(ResultSet resultSet) throws SQLException {
return StreamSupport.stream(new ResultSetSpliterator(resultSet), false).onClose(() -> safeClose(resultSet));
}
public static void safeClose(AutoCloseable closeable) {
try {
closeable.close();
} catch (Exception e) {
log.warn("Can't close {}", closeable.getClass(), e);
}
}
@RequiredArgsConstructor
private final static class ResultSetSpliterator implements Spliterator<ResultSet> {
private final ResultSet resultSet;
@SneakyThrows
@Override
public boolean tryAdvance(Consumer<? super ResultSet> action) {
if (resultSet.next()) {
action.accept(resultSet);
return true;
}
return false;
}
@Override
public Spliterator<ResultSet> trySplit() {
return null;
}
@Override
public long estimateSize() {
return MAX_VALUE;
}
@Override
public int characteristics() {
return ORDERED | NONNULL;
}
}
}
class Test {
private final static Callable<Connection> connectionProvider;
public static void main(String... args) throws Exception {
try (var humans = JdbcStream.of(connectionProvider, "select name from human")) {
humans.map(Human::from).forEach(this::handle);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment