Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query Google App Engine Datastore with Key.Id

I'm deploying a simple Java app to Google App Engine.

I have a simple JPA Entity containing a Key as my generated ID.

import javax.persistence.*;    

@Entity
public class MyEntity
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)    
    private com.google.appengine.api.datastore.Key key;
...

Once I persisted this object. I can view the key's ID like so...

long id = entity.getKey().getId();

Do you know how I can I use the same Id to get my entity back? Something like this...

Query query = em.createQuery("SELECT e FROM MyEntity e WHERE e.key.id = :myId");
query.setParameter("myId", id);

The above doesn't work. I know I can get it back by passing in the Key as the parameter, but I'd like to know if I could use the long id instead.

like image 444
StackEng2010 Avatar asked Dec 06 '22 01:12

StackEng2010


2 Answers

Found the solution, create a Key using the KeyFactory and pass in the ID. Then Query on Key.

Key key = KeyFactory.createKey(MyEntity.class.getSimpleName(), id);
like image 68
StackEng2010 Avatar answered Dec 07 '22 14:12

StackEng2010


There's no need to do a query at all, as the datastore natively supports fetching an entity by its key, which is substantially faster than doing a query. See this section of the docs.

like image 20
Nick Johnson Avatar answered Dec 07 '22 14:12

Nick Johnson