package io.trygvis.async; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; public class SqlEffectExecutor { private final DataSource dataSource; public SqlEffectExecutor(DataSource dataSource) { this.dataSource = dataSource; } public A transaction(SqlEffect effect) { /* int pid; try (Connection c = dataSource.getConnection()) { try (Statement statement = c.createStatement()) { ResultSet rs = statement.executeQuery("SELECT pg_backend_pid()"); rs.next(); pid = rs.getInt(1); } System.out.println("pid = " + pid); try { effect.doInConnection(c); c.commit(); } catch (SQLException e) { c.rollback(); e.printStackTrace(); } finally { System.out.println("Closing pid=" + pid); try { c.close(); } catch (Exception e) { e.printStackTrace(); } } } catch (SQLException e) { e.printStackTrace(); throw new SqlExecutionException(e); } */ try (Connection c = dataSource.getConnection()) { boolean ok = false; try { A a = effect.doInConnection(c); c.commit(); ok = true; return a; } finally { if (!ok) { c.rollback(); } } } catch (SQLException e) { throw new SqlExecutionException(e); } } public void transaction(final SqlEffect.Void effect) { transaction(new SqlEffect() { @Override public Object doInConnection(Connection c) throws SQLException { effect.doInConnection(c); return null; } }); } public static class SqlExecutionException extends RuntimeException { public final SQLException exception; public SqlExecutionException(SQLException ex) { super(ex); this.exception = ex; } } }