7

To identify my JDO objects in Google App Engine I use the Key type. It works fine but when I need to pass this through urls it gets sort of long.

For example: http://mysite.com/user/aghtaWx1LWFwcHIZCxIGTXlVc2VyGAMMCxIHTXlJbWFnZRgHDA

When viewing my entities in my admin viewer I can see that the data-store also sets an "id" for my entity object, which seems to be an incremental numeric value, which is quite short compared to the Key string. Can I use this to grab information on my object? How do I do this? I tried using getObjectbyId() with the id instead of the key... it doesn't work.

Any ideas?

Luca Matteis
  • 29,161
  • 19
  • 114
  • 169

2 Answers2

9

Yes, you can do that. Whenever you need to get the ID you can use the following method call. Assume you are using an object of the entity class User named user: user.getKey().getId(). The id is of type long. See the JavaDoc of com.google.appengine.api.datastore.Key for more information.

Whenever you have the ID you can build the Key from it and then simply query for the object.

Key key = KeyFactory.createKey("User", id);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
User user = datastore.get(key);
Benjamin Muschko
  • 32,442
  • 9
  • 61
  • 82
  • The `id` is actually a string, and it's the value that is visible in the data-store under the `ID/Name` column. Using your code with that doesn't work. I get something like: `Could not retrieve entity of kind User with key User("50")` – Luca Matteis Apr 05 '11 at 15:45
  • 1
    What you see there is the decoded entity key. If you haven't done so you have to parse the ID parameter String in your controller code (e.g. Servlet). Something like this would work in a Servlet: `Long.parseLong(httpServletRequest.getParameter("id")`. Do you see an entity with ID 50 in the datastore viewer? – Benjamin Muschko Apr 05 '11 at 16:04
  • Sorry, my fault. You have to use a String (name of entity kind) when creating the key. Corrected the code above. – Benjamin Muschko Apr 05 '11 at 16:13
2

You will need to define the id in your Entity as a primary key:

private class MyObject implements Serializable{
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;
}

Then you can try this:

long id = someObject.getId();

MyObject mo = getPM().getObjectById(MyObject.class, id);
Yasser
  • 1,808
  • 12
  • 18