Java SE API
Connection.setAutoCommit
Disable automatic commit for explicit transaction ownership. Actual database execution NOT RUN.
Formal Syntax & Structure
java syntaxjava
c.setAutoCommit(false)Working Example
Example Snippetjava
import java.sql.Connection;import java.sql.SQLException;
public final class Tx { private Tx() {} @FunctionalInterface public interface Work { void run() throws SQLException; }
// Requires a freshly borrowed connection in auto-commit mode. // Caller closes it; do not reuse it after a failed rollback. public static void run(Connection c, Work work) throws SQLException { if (!c.getAutoCommit()) throw new SQLException("transaction already active or configured"); c.setAutoCommit(false); try { work.run(); c.commit(); } catch (SQLException | RuntimeException | Error failure) { try { c.rollback(); } catch (SQLException rollbackFailure) { failure.addSuppressed(rollbackFailure); } throw failure; } // No setAutoCommit(true) on failure: it could commit unfinished work. // The owning caller must close; a pool must reset/discard appropriately. }}