2011-03-28 41 views
2

我想在java中實現類似於事務的事務。我想做'n'的操作,比如一個操作更新數據庫,一個插入隊列,一個操作更新另一個數據結構等等,所有這些操作都應該像一個事務一樣,即如果成功,所有的操作都應該成功完成,否則,如果一個失敗了,一切都會失敗。蠻力方法之一是編寫try-catch塊並恢復catch塊中的所有操作。解決這類問題的任何指針?有沒有任何模式或圖書館來實現這一目標?像Java編程這樣的事務

+1

JTA .............. – 2011-03-28 12:37:32

+0

您可以改變你的邏輯,所以它是失敗的tolerent。許多現實世界的系統用戶不是事務性的,你可能會發現你可以解決這個問題,而不是嚴格執行事務。 – 2011-03-28 12:43:19

回答

1

我認爲你正在尋找的模式是Command

Transactional behavior 

Similar to undo, a database engine or software installer may keep a list of operations that have been or will be performed. Should one of them fail, all others can be reverted or discarded (usually called rollback). For example, if two database tables which refer to each other must be updated, and the second update fails, the transaction can be rolled back, so that the first table does not now contain an invalid reference. 
5

不,你想要JTA。

蠻力的方式是使用JDBC並自己管理提交和回滾。

最簡單的方法是使用Spring或EJB3.1和聲明式事務。

+0

+1表示春天 – 2011-03-28 12:40:50

+0

**「如果成功了,所有的操作都應該成功完成,否則,如果一個失敗了,一切都會失敗」**,爲什麼他需要比Connection.commit更多的東西? – PeterMmm 2011-03-28 12:41:42

+0

這些操作可能不僅涉及數據庫事務..它可能包括更新數據庫,插入到隊列等等, – Teja 2011-03-28 17:13:51

0

訪客模式效果很好。 也需要確保您在正確的時間提交提交。如果您等到完成插入/更新的集合,然後發出提交,則您所描述的行爲應該是自動的。

聽起來像也許你需要你的SQL staement類的一個小重構,以確保你可以發出一些沒有暗示的提交語句。

0

這只是一個關於如何實現這一點的邏輯。

根據需要爲每個事務編寫一個方法。可能它會擁有所有的資源。像jdbc事務一樣,將Connection對象和查詢作爲一個需求,文件操作(如果有的話)將有文件路徑,等等。

因此對於5次交易,將會有5種不同的方法。你也可以用一種方法實現它,但這只是爲了簡單。

例如

method1(...) throws Exception { 
    ... 
    // if any exception occurs then control will be passed to caller of this 
    // method 
    throw new Exception("1"); // write method number 
} 

然後寫一個方法(以下僅僅是一個模板):

public long/void transaction(...) throws Exception 
{ 
    try { 
     this.method1(...); 
     this.method2(...); 
     this.method3(...); 
    } catch (Exception e) { 
     // get that number in a exception message 
     // and try to undo all operations numbers less than above number. 
     // e.g. if that transaction method is any database transaction then 
     // try to rollback it. 
     // if it is creation of any file say log file then delete it 
     // now further logic depends on what the transaction was and how to 
     // undo it... 
    } 
} 

感謝。

1

我已經完成了這個命令和複合設計模式的組合。 Transaction類是抽象的,包含begin()& rollback()方法。 CompositeTransaction派生自Transaction,並存儲Transaction對象列表。對於需要作爲原子事務處理的每個操作組,請創建CompositeTransaction的子類並將Transaction類添加到該事務類中。在這裏看到CompositeTransaction:

http://hillside.net/plop/plop99/proceedings/grand/plop_99_transaction_patterns.pdf