
net.dongliu.dbutils.TransactionContext Maven / Gradle / Ivy
package net.dongliu.dbutils;
import net.dongliu.dbutils.exception.UncheckedSQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
/**
* For holding transaction
*
* @author Liu Dong
*/
public class TransactionContext implements SQLExecutor {
private static Logger logger = LoggerFactory.getLogger(TransactionContext.class);
// for backup/restore origin auto commit value
private final boolean autoCommit;
private final Connection connection;
TransactionContext(Connection connection) {
this.connection = Objects.requireNonNull(connection);
try {
this.autoCommit = connection.getAutoCommit();
this.connection.setAutoCommit(false);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
}
}
@Override
public SQLContext withClause(String clause) {
return new SQLContext().withClause(clause).withConnection(connection).withCloseConn(false);
}
/**
* Roll back transaction
*/
public void rollback() {
logger.debug("Rollback Transaction");
try {
connection.rollback();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
restoreConnection();
}
}
/**
* Commit transaction
*/
public void commit() {
logger.debug("Commit Transaction");
try {
connection.commit();
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
restoreConnection();
}
}
/**
* called when transaction ended
*/
private void restoreConnection() {
try {
connection.setAutoCommit(autoCommit);
} catch (SQLException e) {
throw new UncheckedSQLException(e);
} finally {
Closeables.closeQuietly(connection);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy