Created
March 21, 2014 01:48
-
-
Save seratch/9677898 to your computer and use it in GitHub Desktop.
Simple DB utility prototype on Java8
This file contains hidden or 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
$ javac -version | |
javac 1.8.0 | |
$ javac DB.java | |
$ java DB | |
Query: 'select name from members' with connection: DB$Connection@23fc625e | |
closed | |
Alice | |
Bob |
This file contains hidden or 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
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