【问题标题】:How to get an entity that has parent reference?如何获取具有父引用的实体?
【发布时间】:2016-08-17 14:18:19
【问题描述】:

在我的 Spring 项目中并使用 Google App Engine,我试图从数据存储区获取一个实体,但在这种情况下,这个实体有一个 @Parent 关系。我只有实体的 id,这一点不知道有关 Parent 关系的信息。 我尝试了不同的查询,使用ancestorfilterKey,此时我有这个:

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

我的模型是这样的:

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

  //other attributes

  @Index
  @Parent
  public Key<User> createdBy;

  //methods getter and setters
}

当我执行查询时,它返回给我和空实体。但数据存储区的 id 存在。

【问题讨论】:

标签: java google-app-engine objectify google-cloud-datastore


【解决方案1】:

每个实体都有一个键,其中包括其所有祖先的种类、ID/名称和种类 + ID/名称。如果您在未传递祖先信息的情况下创建密钥,则此密钥将与您尝试检索的实体不同

另外请注意,您可以拥有许多具有相同种类和 ID 的实体,如果它们有不同的父级。

【讨论】:

    【解决方案2】:

    只有两种方式:

    //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();
    

    既然你提到你不认识父母。您可以改用 webSafeString - 请参阅 Key.toWebSafeString() 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-07
      • 2021-01-18
      • 1970-01-01
      相关资源
      最近更新 更多