2016-04-19 22 views
0

在Java中執行事務的慣用方式是什麼?我有一些代碼Java中的事務塊?

myObject oldVar = myVar.toMyObject(); 
myVar.mutationAndDBInsertion; 
myObject newVar = myVar.toMyObject(); 

我想換這一切都在一個事務塊,讓我深信myVar對象不會發生變異,除非數據庫的操作是成功的,而oldVarnewVar將是準確的在突變之前和之後的對象狀態的表示。我應該如何處理這個問題?

+0

如果失敗,你可能會有'mutationAndDBInsertion'引發異常。然後下一個陳述將不會被達成。至於確保任何內存中的對象不會改變狀態,Java本身沒有任何東西可以阻止它(或使它成爲事務)。 – Thilo

+0

在您使用數據庫時,請使用數據庫工具(例如SQL,關係數據庫)實現事務。如果SQL事務成功提交,然後在您的Java代碼中處理它。否則,數據庫引擎將回滾事務,並且不需要爲此編寫Java代碼。 –

回答

0

提交事務

後,自動提交模式被禁止,直到調用commit方法沒有明確的SQL語句被提交。之前調用方法提交後執行的所有語句都包含在當前事務中並作爲一個單元一起提交。以下的方法,CoffeesTable.updateCoffeeSales,其中con是活動連接,示出了事務:

公共無效updateCoffeeSales(HashMap中salesForWeek) 從ORACLE拋出的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); 
} 

}

WEB頁面