msk msk - 3 months ago 33
Java Question

how to insert multiple records from json string into google datastore in java

whenever I receive json string as request, I have to insert it into datastore entities.Following is the sample code to read json string and store into entity.

DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Key abckey = KeyFactory.createKey("aaa","aaa1");
Entity abcentity = new Entity(abckey);
JSONArray abc;
Iterator iter = abc.iterator();
while (iter.hasNext()) {
innerObj = (JSONObject) iter.next();
abcentity.setProperty("id",Integer.parseInt(innerObj.get(
"id").toString()));
abcentity.setProperty("mid", Integer.parseInt(innerObj
.get("mid").toString()));
abcentity.setProperty("status", 1);
abcentity.setProperty("tid", touserid);
ds.put(abcentity);

}


It is iterating the json array as long as there are records. But in the google admin console, it shows only the last record. Is this the right way of inserting multiple records into datastore? If not please suggest me some solution.

Answer

It's because you create it only once.

Try this:

DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
JSONArray abc;
Iterator iter = abc.iterator();
while (iter.hasNext()) {
   innerObj = (JSONObject) iter.next();
   // create
   Key abckey = KeyFactory.createKey("aaa",Long.parseLong(innerObj.get(                                                                    
                    "id").toString()));
   Entity abcentity = new Entity(abckey);

   // fill with data
   // ...
   // abcentity.setProperty ...
   //

   // save
   ds.put(abcentity);
}

Key is an Identifier of your entity, not a field called id