Yash Agarwal Yash Agarwal - 3 months ago 11
Java Question

Is it possible to store List<Key> as property of a Entity in Google App Engine (GAE)?

List<Key> items = new ArrayList<Key>();
user.setProperty("ItemsList", items);


The code given above does not work. What are the ways in which this can be achieved using Java platform in GAE ?

P.S. Though the following piece of code runs fine -

List<String> items = new ArrayList<String>();
user.setProperty("ItemsList", items);

Answer

It should work without any problems. Did you forget to put the item? If you didn't set id for the item, the DataStore will automatically assign the entity an integer numeric ID. You need to put that generated key into the list. Here is the sample code:

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity item = new Entity("Item");
datastore.put(item);        

Entity user = new Entity("User");
List<Key> items = new ArrayList<Key>();
items.add(item.getKey());
user.setProperty("ItemsList", items);
datastore.put(user);

Please check the doc: https://developers.google.com/appengine/docs/java/datastore/entities

And, it is better to handle data layer via some third part API like Objectify: http://code.google.com/p/objectify-appengine/