Pawel Uchida-Psztyc
Pawel Uchida-Psztyc

Reputation: 3838

Objectify query by raw datastore Key

I'm having trouble with understanding the upgrade process from JDO to Objectify.

So I have this class:

@PersistenceCapable
public class AppUser { 
    /**
     * key from userID
     */
    @PrimaryKey
    @Persistent
    private Key key;

    //...
}

And I upgraded it to:

@Entity
public class AppUser { 
    /**
     * key from userID
     */
    @Index Key key;
    @Id Long id;

    // ...
}

Before the change I was able to retrieve the entity using following method:

Key _key = KeyFactory.createKey(AppUser.class.getSimpleName(), user.getUserId());
PersistenceManager pm = PMF.get().getPersistenceManager();
AppUser appUser = pm.getObjectById(AppUser.class, _key);

Where user object is AppEngine's user object referenced with Google Account.

How can I query for an entity for given user? When I try to use filterKey it results with null object. Thanks in advance.

Upvotes: 0

Views: 381

Answers (1)

konqi
konqi

Reputation: 5217

Currently your key attribute is just an indexed attribute, therefor you should be able to query for it with

ofy().load().type(AppUser.class).filter("key", Key.create(AppUser.class, id)).list();

I get the feeling that this is not what you're looking for since you don't have an id and a key property in your above code sample. Also the Key property would be a reference to another entity which i don't see in your first code sample. So i assume that you really only want to use the id. Now i don't know whether your key is numeric or a string, but i assume you're looking for something like this:

@Entity
public class AppUser { 
    @Id Long key; // you can replace Long with String if your ids are strings
}

You would then query by id, like so

ofy().load().type(AppUser.class).id(userIdOrName).list();

alternatively a key query would look like this

ofy().load().key(Key.create(AppUser.class, userIdOrName));

Upvotes: 1

Related Questions