通过键或 ID 查询单个实体的对象化

Querying objectify for a single entity by key or id

给定键或 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];

    }

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

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

如果您已有密钥:

ofy().load().key(dogKey).now();
  • 另请注意 ofy
  • static import
  • 如果您宁愿捕获异常而不是检查空 return 值,您可以用 now() 代替 safe()

文档很好地概述了 Basic Operations

编辑

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

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