【问题标题】:Objectify entity relationship实体化实体关系
【发布时间】:2017-01-06 13:25:39
【问题描述】:

我是 Android 的初学者,我正在尝试了解 GAE 如何与 Objectify 一起工作。

所以我创建了两个类,一个是“用户”,另一个是“旅程”。每个旅程都属于一个用户。

用户类

@Entity
public class User {
    @Id
    private Long id;
    @Index private String mac;
    private String name;
    private String firstName;
    private Long age;
    private String email;
    private String password;
// Getters and setters
}

旅程班

@Entity
public class Journey {
    @Id
    private Long id;
    Key<User> driver;
    private Event event;
    private Long nbPlaces;
    private String departureTime;
    private String destination;
}
  1. 我在User类上写了如下方法,这样对吗?

    @瞬态 密钥 getKey() { 返回 Key.create(User.class, id); }

  2. 如何在我的旅程对象中设置用户的密钥? (我想我不能使用简单的 setter。

谢谢!

【问题讨论】:

    标签: android google-app-engine objectify


    【解决方案1】:

    先前声明:

    import static com.googlecode.objectify.ObjectifyService.ofy;
    

    获取对象:

    public User get(Long id) {
         return ofy().load().key(Key.create(User.class, id)).now();
    }
    

    而要将User中的Key设置成Journey类,需要在对象创建时传入构造函数,或者获取对象Journey设置参数并保存。但是您需要事先获取密钥:

    public Long getKey(User user) {
         Key<User> generatedKey = ofy().save().entity(user).now();
         return generatedKey.getId();
    }
    

    之后,您可以将Users 的列表附加到Journeyclass 中。

    【讨论】:

    • 感谢您的回答。但我不知道我必须在哪里粘贴这段代码。在实体中还是在端点中?抱歉,我是新手。
    • 在您的端点中。这里有更多对你有用的信息:rominirani.com/…
    • 好的,所以我必须使用您编写的第一个代码将生成的 get 方法覆盖到用户端点中,对吗?我必须在哪里编写代码的第二部分?我无法将此方法放入 Endpoint,因为 Endpoint 方法无法返回原始类型..
    • 第一个问题的答案是肯定的。第二部分仅返回为该 User 对象生成的 Key,因此您可以将原始类型更改为 long。我不清楚如何将 User 的引用保存到 Journey 中,但是一旦获得对象或正确返回 Key,就可以通过不同的方式实现它。
    • 您好,感谢您的回答 :-) 我如何直接与您联系以谈论此事?
    猜你喜欢
    • 1970-01-01
    • 2012-06-23
    • 2012-05-21
    • 2015-07-27
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 2017-05-23
    相关资源
    最近更新 更多