简体   繁体   中英

GAE: JAVA- update only one field in a particular row of an entity

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM