【问题标题】:Querying objectify for a single entity by key or id通过 key 或 id 查询单个实体的 objectify
【发布时间】:2016-06-04 18:08:31
【问题描述】:

给定一个键或一个 ID,我想查询单个实体的对象化。我该怎么做?我正在使用以下方法,我觉得很麻烦。是否有单线替代方案?到目前为止,这是我的方法:

public static Dog getDog(String id) {

        log.info(TAG+": getDog");
    
    Key<Dog> key = Key.create(Dog.class, id);

        Map<Key<Dog>, Dog> result = OfyService.ofy().load().keys(key);

        return (Dog) result.values().toArray()[0];

    }

【问题讨论】:

标签: google-app-engine objectify


【解决方案1】:

假设你的实体没有祖先,你想要:

ofy().load().type(Dog.class).id(dogId).now();

如果你有一个现有的密钥:

ofy().load().key(dogKey).now();
  • 还要注意ofystatic import
  • 如果您希望捕获异常而不是检查返回值是否为空,则可以将 now() 替换为 safe()

文档对Basic Operations 进行了很好的概述。

编辑

你说你的实体确实有一个祖先,所以你需要指定父级,像这样:

Dog otherDog; // this is your ancestor
ofy().load().type(Dog.class).parent(otherDog).id(dogId).now();

【讨论】:

  • 我的实体确实有父母。但是 id 是一个字符串。那怎么做ofy().load().type(Dog.class).id(dogId).now();还不够呢?当我这样做时,查询失败并返回 null。我总是必须先创建一个键来包含父级。
  • 在这种情况下,type(Dog.class).id(dogId) 将不包含足够的信息来形成密钥,您需要指定祖先路径(顺便说一句,您的原始示例没有这样做)。我会相应地更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多