如何存储用户拥有的数据?

How to store data owned by User?

我正在学习 Google App Engine + Google Cloud Endpoints + Objectify 并且我正在尝试了解如何创建 REST API 让每个特定用户保存他的数据在云端。

我目前的难题是如何存储用户拥有的实体 (com.google.appengine.api.users.User)?

到目前为止我有端点:

@ApiMethod(name = "saveBook")
public void saveBook(Book book, User user) throws OAuthRequestException, IOException {
    if (user == null) {
        throw new OAuthRequestException("User is not authorized");
    }

    ofy().save()
            .entity(BookRecord.fromBook(user, book))
            .now();
}

实体(在此上下文中,我们假设 User 写了这本书):

@Entity
public class BookRecord {

    @Parent
    private Key<User> user;
    @Id
    private String id;
    @Index
    private String name;

    public static BookRecord fromBook(User user, Book book) {
        return new BookRecord(
                Key.create(user),
                book.getId(),
                book.getName()
        );
    }

    public BookRecord() {
    }

    private BookRecord(Key<User> user, String id, String name, String author) {
        this.user = user;
        this.id = id;
        this.name = name;
        this.author = author;
    }

}

问题是由于 User 不是 Entity,所以我不能真正使用这个解决方案并直接将 User 用作 @Parent。解决此问题并存储用户拥有的数据的一般解决方案是什么?

创建您自己的 User 实体,这是您为您的应用存储自定义 information/preferences 的地方(正如我所建议的 )。

您将使用 getUserId() 将它与 Google 用户绑定,然后您可以根据需要自由使用它。