Joel Blum
Joel Blum

Reputation: 7888

Duplicate entries with Google datastore

I am using Google App Engine with the Datastore interface.

Whenever I'm trying to update an entity, a whole new entity is created, this is despite the fact that I'm positive I am saving the same entity, meaning it has the same key for sure.

This is my code:

Key key=KeyFactory.createKey("user",Long.parseLong(ID));
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Entity entity=new Entity("user",key);
entity.setProperty // ...whatever, updating the properties
datastore.put(entity); //by putting an entity it's supposed to
// either create a new one if non exists, or update an entity if it already exists

I am sure that the key is the same during all updates as is confirmed in my admin console:

id=3001   600643316
id=3002   600643316
id=3003   600643316 

a bunch of entities with the same key (600643316) is created.

Upvotes: 1

Views: 2404

Answers (2)

Joel Blum
Joel Blum

Reputation: 7888

So it seems Dan is correct and this is the correct way to do it , as explained in google's guides if you want your app to build keys from unique keys that you create you need to use strings . "You specify whether an entity ought to use an app-assigned key name string or a system-assigned numeric ID as its identifier when you create the object. To set a key name, provide it as the second argument to the Entity constructor: Entity employee = new Entity("Employee","asalieri");" It seems you're correct , in their example the second argument is indeed a string – user1032663

Upvotes: 0

Dan Sanderson
Dan Sanderson

Reputation: 2111

The datastore only lets the app create a new entity with a String key name, not a numeric ID. Numeric IDs are system-assigned IDs. If the Key has a numeric ID but not a String key name, then the datastore will ignore it and replace it with a system-assigned numeric ID.

In your example, if ID is a string, then you can just remove the Long.parseLong() bit, or convert it back to a String. KeyFactory.createKey(String kind, String name) creates a Key with a key name.

Upvotes: 1

Related Questions