Question

I am trying to use the App Engine Datastore (High Replication Datastore, HRD) and i have to use the low-level API . I never worked with entity database before so I have some problem. I have tried to store some Post and comments, each post can have more comments

I tried this code for Post, but the problem is how to make ID auto-increment ?
Entity post = new Entity("post", ID);
post.setProperty("content", postContent);
post.setProperty("time", timeStamps);

And this code for comment but i don't understand how to use the ancestor to make the relation between the post and the the comment, shall i just add ancestor property and put the ID value on it ?

Entity comment = new Entity("comment", ID);
comment.setProperty("ancestor",postID);
comment.setProperty("content", commentContent);
comment.setProperty("time", timeStamps);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(comment);
Was it helpful?

Solution

to use auto-increment feature you need to change the config of your app to use legacy keygeneration:

<auto-id-policy>
 legacy
</auto-id-policy>

then you can change your code to the following:

Entity post = new Entity("post");
post.setProperty("content", postContent);
post.setProperty("time", timeStamps);

if you dont pass the ID, appengine will generate it

to use ancestor path you can change your code to the following:

datastore.put(post);    
Entity comment = new Entity("comment", post.getKey());
comment.setProperty("content", commentContent);
comment.setProperty("time", timeStamps);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(comment);

the ancestor key will be put as a Constructor arg.

instead of auto-increment i would recommend you to use the default key generation, with is not a increment but still unique,
also it should be faster, then legacy

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top