按 "key" 字段过滤 Objectify 查询

Filter Objectify query by "key" field

我有以下对象化关系:

@Entity(“Author”)
public class Author{
  @Id
  private long authorId;
  …

}

@Entity(“Book”)
public class Book{
  @Id
  private long id;
  private Key<Author> authorKey;
  …

}

现在是有趣的部分:我有 authorId(ID,不是实体),我需要为该作者查询 Book。我的查询在下面,但它返回一个空列表,而我确实知道该作者在数据存储区中有书籍。那么我该如何解决这个问题呢?

public static List<Book> getBooksForAuthor(Long authorId) {
    Key<Author> authorKey = Key.create(Author.class, authorId);
    return OfyService.ofy().load().type(Book.class).filter("authorKey", authorKey).order(“-date").list();
  }

您将需要 @Index Book.authorKeyBook.date 字段。我不记得这是否需要在 {authorKey, date} 上使用多属性索引,但请尝试一下,看看它是否有效。

我还建议您将该字段称为 'author' 而不是 'authorKey'。

您正在查询字段 authorId 而不是您刚刚创建的 authorKey

OfyService.ofy().load().type(Book.class).filter("authorKey", authorKey).order(“-date").list();

有了这个更改和索引,您应该会得到结果。