Skip to content

Instantly share code, notes, and snippets.

@seratch
Created March 21, 2014 01:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seratch/9677898 to your computer and use it in GitHub Desktop.
Save seratch/9677898 to your computer and use it in GitHub Desktop.
Simple DB utility prototype on Java8
$ javac -version
javac 1.8.0
$ javac DB.java
$ java DB
Query: 'select name from members' with connection: DB$Connection@23fc625e
closed
Alice
Bob
import java.util.function.Function;
import java.util.*;
public class DB {
static void println(String s) { System.out.println(s); }
// java.sql.Connection
static class Connection implements AutoCloseable {
@Override public void close() { println("closed"); }
}
static class ConnectionPool {
static Connection borrow() { return new Connection(); }
}
public static <R> R transaction(Function<Connection, R> f) {
try (Connection conn = ConnectionPool.borrow();) {
return f.apply(conn);
}
}
// sample DAO
static class MemberDao {
private Connection conn;
MemberDao(Connection conn) { this.conn = conn; }
List<String> findAllNames() {
println("Query: 'select name from members' with connection: " + conn);
return Arrays.asList("Alice", "Bob");
}
}
public static void main(String[] args) {
List<String> names = DB.transaction((tx) -> {
return new MemberDao(tx).findAllNames();
});
names.forEach(n -> println(n));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment