客观化实体关系

时间:2016-08-30 10:01:51

标签: android google-app-engine objectify

我是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类上写了以下方法,这是正确的吗?

    @Transient Key getKey(){     return Key.create(User.class,id); }

  2. 如何在旅程对象中设置用户密钥? (我想我不能用一个简单的二传手。

  3. 谢谢!

1 个答案:

答案 0 :(得分:0)

先前声明:

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

获取对象:

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

要将密钥从User设置为Journey类,您需要在创建对象时传入构造函数,或者获取对象Journey设置参数并保存它。但是你需要先获得Key:

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

在此之后,您可以将Users的列表附加到Journey类。