user6249222
user6249222

Reputation:

How to get an entity that has parent reference?

In my Spring project and using Google App Engine, I'm trying to get an entity from datastore, but in this case this entity has a @Parent relation. I only have the id from the entity, a this point unaware information about Parent relation. I tried different querys, using ancestor filterKey, at this moment I have this:

@Override
public House getNotRestrictions(Long id){
      return objectifyService.ofy().load().type(House.class).filterKey(Key.create(House.class, id)).first().now();
}

My model is something like this:

@Entity
public class House {
  @Id
  public Long id;

  //other attributes

  @Index
  @Parent
  public Key<User> createdBy;

  //methods getter and setters
}

When I execute the query, it returns to me and null entity. But the id into the datastore exists.

Upvotes: 1

Views: 388

Answers (2)

F&#225;bio Uechi
F&#225;bio Uechi

Reputation: 837

There are only two ways:

//1. creating the full key with parent:
Key<House> houseKey = Key.create(Key.create(User.class, userId), House.class, id);

//2. or using the webSafeString key representation which contains the whole key path including namespace and parents:
String webSafeKey = "<encoded key as string>";
Key<House> houseKey = Key.<House>create(webSafe)

//Then you can fetch the entity:
House house = ofy().load().key(houseKey).now();

Since you mentioned you don't know the parent. You could start using the webSafeString instead - see Key.toWebSafeString() method

Upvotes: 0

Andrei Volgin
Andrei Volgin

Reputation: 41099

Every entity has a key that includes its kind, ID/name, and kind + ID/name of all of its ancestors. If you create a key without passing ancestor information, this key will be different from the entity you are trying to retrieve.

Also note that you can have many entities with the same kind and ID, if they have different parents.

Upvotes: 1

Related Questions