通过密钥或id查询单个实体的客观化

时间:2016-06-04 18:08:32

标签: google-app-engine objectify

给定一个密钥或一个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];

    }

1 个答案:

答案 0 :(得分:1)

假设您的实体没有祖先,您需要:

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

如果您有现有密钥:

ofy().load().key(dogKey).now();
  • 另请注意static import
  • ofy
  • 如果您要检查异常而不是检查空返回值,则可以将now()替换为safe()

文档非常好地概述了Basic Operations

修改

您说您的实体 有祖先,因此您需要指定父级,如下所示:

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