I am not sure if I am understanding the google documentation, I am wondering if someone else can check my understanding.
Is the following code guaranteed to only ever do both of the following:
- update to the bank account balance
- store a record of the transaction.
Below is what I understand is correct:
public void add(String account, Double value, String description, Date date) throws EntityNotFoundException {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
int retries = 3;
while (true) {
Transaction txn = datastore.beginTransaction();
try {
// Update the bank balance
Key key = KeyFactory.createKey("Account", account);
Entity e = datastore.get(key);
Double balance = (Double) e.getProperty("balance");
balance += value;
e.setProperty("balance", value);
datastore.put(e);
// Record transaction details
Entity d = new Entity("Transaction", key);
d.setProperty("account_key", key);
d.setProperty("date", date);
d.setProperty("value", value);
d.setProperty("description", description);
txn.commit();
break;
} catch (ConcurrentModificationException e) {
if (retries == 0) throw e;
retries--;
} finally {
if (txn.isActive()) txn.rollback();
}
}
}
}
That’s correct. It’s not necessary to include the key of the account in the entity, though – the entity you’re creating is a child of the account in question.