I found solution to rollback transaction when commit fails and It works perfectly. But could you explain why Autorollback object close method is called first than connection close?
Autorollback class :
public class AutoRollback implements AutoCloseable {
private Connection conn;
private boolean committed;
public AutoRollback(Connection conn){
this.conn = conn;
}
public void commit() throws SQLException {
conn.commit();
committed = true;
}
@Override
public void close() throws SQLException {
if(!committed) {
conn.rollback();
}
}
}
example of service method that use Autorollback:
try(Connection connection = MySQLDAOFactory.getConnection();
AutoRollback autoRollback = new AutoRollback(connection)){
result = carDao.insertCar(connection,car);
autoRollback.commit();
} catch (SQLException | NamingException | MySQLEXContainer.MySQLDBExecutionException throwables) {
throw new ApplicationEXContainer.ApplicationCanNotChangeException(throwables.getMessage(),throwables);
}
Why does Autorollback's close method works?If connection is closed how can it call rollback method?So the only explanation is autorollback close method is called earlier thah connection close, but why?