Instinct
Instinct

Reputation: 2261

How do I return an auto generated numeric ID from the key in google app engine?

Heres my code

Entity post = new Entity("Post");
int ID = post.getKey().getId();
post.setProperty("ID", ID);

But the ID shows as 0 in my datastore.

What did I do wrong?

Upvotes: 0

Views: 460

Answers (2)

Alexey Smychagin
Alexey Smychagin

Reputation: 19

You can use method allocateIds to generate unique ID.

Here is an example.

DatastoreService datastoreService = DatastoreServiceFactory.getDatastoreService();

KeyRange keyRange = datastoreService.allocateIds("CartItem", 1L);

// you have ID here before save
Entity item = new Entity(keyRange.getStart());
datastoreService.put(item);

Upvotes: 0

Tim Hoffman
Tim Hoffman

Reputation: 12986

You won't have an id getId() until the entity has been put to the datastore.

Why would you store the id from the Key as an property of an entity. It is completely redundant. Also the id of the key can't be changed re-inforcing redundancy.

Upvotes: 3

Related Questions