JDBC 为什么需要在事务管理中手动回滚?

Why need of manual rollback in transaction management by JDBC?

此代码是我从 oracle 站点获取的用于事务管理的代码。事务失败数据库会自动回滚,为什么要手动回滚?

public void updateCoffeeSales(HashMap<String, Integer> salesForWeek)
throws SQLException {

PreparedStatement updateSales = null;
PreparedStatement updateTotal = null;

String updateString =
    "update " + dbName + ".COFFEES " +
    "set SALES = ? where COF_NAME = ?";

String updateStatement =
    "update " + dbName + ".COFFEES " +
    "set TOTAL = TOTAL + ? " +
    "where COF_NAME = ?";

try {
    con.setAutoCommit(false);
    updateSales = con.prepareStatement(updateString);
    updateTotal = con.prepareStatement(updateStatement);

    for (Map.Entry<String, Integer> e : salesForWeek.entrySet()) {
        updateSales.setInt(1, e.getValue().intValue());
        updateSales.setString(2, e.getKey());
        updateSales.executeUpdate();
        updateTotal.setInt(1, e.getValue().intValue());
        updateTotal.setString(2, e.getKey());
        updateTotal.executeUpdate();
        con.commit();
    }
} catch (SQLException e ) {
    JDBCTutorialUtilities.printSQLException(e);
    if (con != null) {
        try {
            System.err.print("Transaction is being rolled back");
            con.rollback();
        } catch(SQLException excep) {
            JDBCTutorialUtilities.printSQLException(excep);
        }
    }
} finally {
    if (updateSales != null) {
        updateSales.close();
    }
    if (updateTotal != null) {
        updateTotal.close();
    }
    con.setAutoCommit(true);
}

}

我也查看了其他一些网站。还进行了手动回滚。我无法理解这一点。请说明。

这里要认识到的主要事情是 两个 单独的更新语句正在完成。最有可能的是,使用显式事务管理的原因是此代码的作者打算让两个更新都原子地。也就是说,预期的逻辑是两个更新都成功、一起或都失败。在后一种情况下,为两次更新所做的一切都应该回滚,使数据库保持其原始状态。因此,虽然使用显式 transaction/rollback 不一定 是必需的 ,但两个更新以原子方式发生是必需的。