0

问题是: ds.put(employee) 是否发生在事务中?或者外部事务是否被 saveRecord(..) 中的事务擦除/覆盖?

  1. 一旦在 for 循环中的某个点(假设 i==5)在 datastore.put(..) 行引发错误,之前源自同一行的 put 会回滚吗?
  2. saveRecord(..) 中发生的 put 怎么样?我想那些不会被回滚。
    DatastoreService 数据存储 = DatastoreServiceFactory.getDatastoreService()
    交易 txn = datastore.beginTransaction();
    尝试 {
        for (int i=0; 1<10; i++) {
            Key employeeKey = KeyFactory.createKey("Employee", "Joe");
            实体员工 = datastore.get(employeeKey);
            employee.setProperty("假期", 10);

            datastore.put(员工);

            实体employeeRecord = createRecord("record",employeeKey);
            保存记录(雇员记录);
        }
    txn.commit();
    } 最后 {
        如果 (txn.isActive()) {
            txn.rollback();
        }
    }

    公共无效保存记录(实体实体){
       datastore.beginTransaction();
       尝试 {
          // 在这里做一些逻辑,删除活动并提交 txn
          datastore.put(实体);
       } 最后 {
        if (datastore.getCurrentTransaction().isActive()) {
          datastore.getCurrentTransaction().rollback();
        }
       }
    }

4

1 回答 1

1

好的,我假设您使用的是低级 Datastore 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();
  }
}

现在开始提问:

  1. 是的,因为所有 put 现在都是同一事务的一部分(在您修复代码之后),并且您txn.rollback()在出现错误时调用它。

  2. 不,当然不是。它们是不同交易的一部分。

于 2012-08-06T20:32:20.847 回答