Objectify 可选地加载引用的属性

Objectify optionally load referenced attributes

我有一个 UserAccount,其中包含以下列表。以下列表保存为它自己的实体。我通常不需要下面的列表,因此,我不使用@Load。但是,我有一种情况,我想加载多个 UserAccounts 及其以下内容。

所以,我需要这样的东西:

OfyService.ofy().load().type(UserAccount.class).limit(200).loadReference("followerRef").list();

UserAccount 示例:

@Entity
@Cache
public class UserAccount {
    @Id private String email;
    @Index
    private String nickname;
    private Ref<UserFollowing> followingRef;
}

我相信 Objectify 已经以 Load Groups 的形式提供了一种方法来完成您想要的事情。正如您正确指出的那样,使用 @Load 注释将自动检索 UserAccountsfollowingRef,这在大多数情况下是您不希望发生的。

为了加载 UserAccount 的列表及其 followingRef,您首先必须对您的实体应用以下简单修改:

@Entity
public class UserAccount {
    public static class Everything {}

    @Id Long id;
    @Load(Everything.class) Ref<UserFollowing> followingRef;
}

然后您可以执行以下操作来加载单个 UserAccount 对象:

// Doesn't load followingRef
UserAccount ua = ofy().load().key(userAccountKey).now();

// Does load followingRef
UserAccount ua = ofy().load().group(Everything.class).key(userAccountKey).now();

类似地,您这样做是为了加载 UserAccount 个对象的列表及其 followinfRef:

// In your case you'd do something like
List<UserAccount> accounts = ofy().load()
                                  .type(UserAccount.class)
                                  .group(Everything.class)
                                  .list();

这应该有望解决您的问题。 我不知道该代码是否可以编译,但如果不能编译应该不会太难修复。

For further reading click here and scroll down to Load Groups section