2012-08-06 75 views
0

問題是:ds.put(employee)是否發生在事務中?或者外部事務是否被saveRecord(..)中的事務清除/重寫?谷歌應用程序引擎數據存儲上的嵌套事務3

  1. 一旦在for循環(假設i == 5)中的某個點處在行datastore.put(..)處引發錯誤,以前的放置將始發在同一行上是否會回滾?
  2. 那麼在saveRecord(..)中發生的情況如何。我想那些不會被回滾。
 

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService() 
    Transaction txn = datastore.beginTransaction(); 
    try { 
     for (int i=0; 1<10; i++) { 
      Key employeeKey = KeyFactory.createKey("Employee", "Joe"); 
      Entity employee = datastore.get(employeeKey); 
      employee.setProperty("vacationDays", 10); 

      datastore.put(employee); 

      Entity employeeRecord = createRecord("record", employeeKey); 
      saveRecord(employeeRecord); 
     } 
    txn.commit(); 
    } finally { 
     if (txn.isActive()) { 
      txn.rollback(); 
     } 
    } 

    public void saveRecord(Entity entity) { 
     datastore.beginTransaction(); 
     try { 
      // do some logic in here, delete activity and commit txn 
      datastore.put(entity); 
     } finally { 
     if (datastore.getCurrentTransaction().isActive()) { 
      datastore.getCurrentTransaction().rollback(); 
     } 
     } 
    } 

+0

是'ds.beginTransaction()'你的自定義代碼嗎?每次通話都會返回相同的交易還是新的交易? – 2012-08-06 15:48:42

+0

ds僅僅是對API DataStore對象的引用。 – honzajde 2012-08-06 18:02:54

+0

我編輯了過於模糊的原始示例...請回答最後一次。謝謝。 – honzajde 2012-08-08 12:36:08

回答

1

OK,我假設你正在使用低級別的數據存儲API。請注意,getTransaction()不存在。我會假設你的意思是datastoreService.getCurrentTransaction()

DatastoreService.beginTransaction()將返回一個交易,該交易被視爲同一線程上的當前交易,直到您再次撥打beginTransaction()。由於您在「外部」事務內的循環中調用beginTransaction(),因此它將打破「外部」代碼:循環結束後ds.getCurrentTransaction()不會返回相同的事務。另外,put()隱式使用當前事務。現在,在

public void put(EventPlan eventPlan) { 
    Transaction txn = ds.beginTransaction(); 
    try { 
    for (final Activity activity : eventPlan.getActivities()) { 
     save(activity, getPlanKey(eventPlan)); // PUT 

     // IMPORTANT - also pass transaction and use it 
     // (I assume this is some internal helper method) 
     ds.put(txn, activity, getSubPlanKey(eventPlan)); //subplan's parent is eventPlan 
    } 
    txn.commit(); 
    } finally { 
    if (txn.isActive()) 
     txn.rollback(); 
    } 
} 

到的問題:

所以,首先你必須修復外碼事務保存爲shown in example

  1. 是的,因爲所有的看跌期權,現在是同一事務的一部分(後你修正了代碼),並且在錯誤的情況下你可以打電話給txn.rollback()。不,當然不是。它們是不同交易的一部分。

+0

我編輯了原來太含糊的示例......請回答上一次... – honzajde 2012-09-02 17:43:52

相關問題