Question is: does ds.put(employee) happen in transaction? Or does the outer transaction get erased/overriden by the transaction in saveRecord(..)?
- Once error is thrown at line datastore.put(..) at some point in the for-loop (let's say i==5), will previous puts originating on the same line get rollbacked?
- What about puts happening in the saveRecord(..). I suppose those will not get rollbacked.
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(); } } }
OK, I'll assume you are using low-level Datastore API. Note that
getTransaction()
does not exist. I'll assume you meantdatastoreService.getCurrentTransaction()
.DatastoreService.beginTransaction()
will return a Transaction, that is considered a current transaction on the same thread until you callbeginTransaction()
again. Since you callbeginTransaction()
in a loop inside "outer" transaction, it breaks your "outer" code: after the loop is finishedds.getCurrentTransaction()
does not return the same transaction. Also,put()
implicitly uses current transaction.So first you must fix outer code to save transaction as shown in example:
Now on to questions:
Yes, because all puts are now part of the same transaction (after you fix the code) and you call
txn.rollback()
on it in case of errors.No, of course not. They are part of different transactions.