Katedral Pillon Katedral Pillon - 1 month ago 10
Java Question

How to perform bulk update on AppEngine Datastore

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

Answer

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