Created
February 17, 2018 05:59
-
-
Save varrix/be1ccdcd04a11db890813693ee1dfbbf to your computer and use it in GitHub Desktop.
AutoRollback class implementing AutoCloseable for some interesting commit changes for a finally-block. Source: https://stackoverflow.com/a/37122747
This file contains 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.sql.SQLException; | |
import java.sql.Connection; | |
public class AutoRollback implements AutoCloseable { | |
private Connection conn; | |
private boolean committed; | |
public AutoRollback(Connection conn) throws SQLException { | |
this.conn = conn; | |
} | |
public void commit() throws SQLException { | |
conn.commit(); | |
committed = true; | |
} | |
@Override | |
public void close() throws SQLException { | |
if(!committed) { | |
conn.rollback(); | |
} | |
} | |
} | |
public class AutoSetAutoCommit implements AutoCloseable { | |
private Connection conn; | |
private boolean originalAutoCommit; | |
public AutoSetAutoCommit(Connection conn, boolean autoCommit) throws SQLException { | |
this.conn = conn; | |
originalAutoCommit = conn.getAutoCommit(); | |
conn.setAutoCommit(autoCommit); | |
} | |
@Override | |
public void close() throws SQLException { | |
conn.setAutoCommit(originalAutoCommit); | |
} | |
} | |
public class ExampleUsage { | |
try(Connection conn = getConnection(), AutoSetAutoCommit a = new AutoSetAutoCommit(conn,false), | |
AutoRollback tm = new AutoRollback(conn)) { | |
// Do stuff | |
tm.commit(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment