SHARE
TWEET

JDBC & Stream API

DulcetAirman Jul 29th, 2018 25 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ch.claude_martin;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.util.Spliterator;
  9. import java.util.Spliterators;
  10. import java.util.function.Consumer;
  11. import java.util.stream.Stream;
  12. import java.util.stream.StreamSupport;
  13.  
  14. class SomeClass {
  15.     public static void main(String[] args) throws Throwable {
  16.         Connection conn = null;
  17.         PreparedStatement stmt = conn.prepareStatement("SELECT * FROM FOO", ResultSet.TYPE_SCROLL_INSENSITIVE,
  18.                 ResultSet.CONCUR_READ_ONLY);
  19.         ResultSet rs = stmt.executeQuery();
  20.         long size;
  21.         try {
  22.             rs.last();
  23.             size = rs.getRow();
  24.             rs.beforeFirst();
  25.         } catch (Exception ex) {
  26.             size = Long.MAX_VALUE;
  27.         }
  28.         Stream<Foo> stream = StreamSupport.stream(new AbstractSpliteratorExtension(rs, size), false);
  29.  
  30.         var result = stream.map(mapper1).map(mapper2).filter(someFilter).collect(myCollector);
  31.     }
  32.  
  33.     private static final class AbstractSpliteratorExtension extends Spliterators.AbstractSpliterator<Foo> {
  34.         private final ResultSet rs;
  35.  
  36.         private AbstractSpliteratorExtension(ResultSet rs, long size) {
  37.             super(size, Spliterator.ORDERED);
  38.             this.rs = rs;
  39.         }
  40.  
  41.         @Override
  42.         public boolean tryAdvance(Consumer<? super Foo> action) {
  43.             try {
  44.                 if (!rs.next())
  45.                     return false;
  46.                 action.accept(Foo.of(rs));
  47.                 return true;
  48.             } catch (SQLException e) {
  49.                 throw new RuntimeException(e);
  50.             }
  51.         }
  52.     }
  53.  
  54.     public static class Foo {
  55.         public static Foo of(ResultSet rs) { ... }
  56.     }
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top