Reputation: 14844
The following code is not working. Does anyone know how I might get it to work?
Query q = new Query("Product");
Iterable<Entity> entities = datastore.prepare(q).asIterable();
for (Entity entity : datastore.prepare(q).asIterable()) {
entity.setProperty(“sale”, false);
}
datastore.put(entities);
sale
is a completely new field that I am adding to the entity kind. So it does not exist yet.
UPDATE
I fixed it as below but the code is still not working
Query q = new Query("Product");
Iterable<Entity> entities = datastore.prepare(q).asIterable();
for (Entity entity : entities) {
entity.setProperty(“sale”, false);
}
datastore.put(entities);
Upvotes: 1
Views: 838
Reputation: 41089
There is an error in your code. You never update entities
. It should be:
Query q = new Query("Product");
List<Entity> entities = datastore.prepare(q).asList(FetchOptions.Builder.withDefaults());
for (Entity entity : entities) {
entity.setProperty(“sale”, false);
}
datastore.put(entities);
Upvotes: 2
Reputation: 2434
Maybe someone else can explain to you why exactly it does not work, but I know how to make it work.
For some reason the entities
iterable does not behave like a proper Java collection. In a Java collection, the elements are pointers. But for whatever reason, here each entity that you get inside the for-loop is an independent deep copy. So instead, do the following and it will work
Query q = new Query("Product");
List<Entity> products = new ArrayList<Entity>();
for (Entity entity : datastore.prepare(q).asIterable()) {
entity.setProperty("sale", false);
products.add(entity);
}
datastore.put(products);
Upvotes: 1