Reputation: 401
The requirement is to update the field of one of the rows in the entity. But the below code is updating entity row. Where am I making a mistake?
//Inserting
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
//Util.getKey() always returns current Date
Key ky=KeyFactory.createKey("Routine", Util.getKey());
Entity e = new Entity("Routine",ky);
e.setProperty("running", Constants.RUNNING_INCREDIBLE);
datastore.put(e);
//Updating
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key ky=KeyFactory.createKey("Routine", Util.getKey());
Entity e2=datastore.get(ky);
e2.setProperty("bAS", Constants.BAS_INCREDIBLE);
datastore.put(e);
Upvotes: 0
Views: 90
Reputation: 4275
There is nothing wrong with your implementation. There is no difference between insert and update in Datastore.
From the documentation:
The Cloud Datastore API does not distinguish between creating a new entity and updating an existing one. If the object's key represents an entity that already exists, the put() method overwrites the existing entity. You can use a transaction to test whether an entity with a given key exists before creating one.
You can refer to the documentation.
Additionally, if you are updating a field too quickly consider using MemCache.
If you want to take care of transactions, look at:
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Transaction txn = datastore.beginTransaction();
try {
Key employeeKey = KeyFactory.createKey("Employee", "Joe");
Entity employee = datastore.get(employeeKey);
employee.setProperty("vacationDays", 10);
datastore.put(txn, employee);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
This is documented here
Upvotes: 2