3

我被坚持和Objectify弄湿了。我想要一些关于分配父键的指导。我的具体问题全部大写。谢谢。(下面的示例模型包含一个 AppUser 和一个视频。这个想法就像 YouTube;用户创建属于他/她的视频。)

@Entity
class Video{
// QUESTION 1: SHOULD THIS CLASS HAVE ONLY 1 KEY FIELD IF I WANT A 
PARENT RELATIONSHIP WITH AppUser, AND TYPE IS Key<AppUser> ?
@Parent Key<AppUser> owner;
@Id private Long id;

protected Video(){}
protected Video(User u){ // GAE User object     
    AppUser au = ofy().load().type(AppUser.class).filter("userId",u.getUserId()).first().get();

    // QUESTION 2: WHICH WAY IS RIGHT (TO ASSIGN PARENT KEY)?
    this.owner = Key.create(au.getKey(),AppUser.class,au.getId()); 
    // or:
    // owner = au.getKey();
    // or:
    // owner = au;
}
}

@Entity
public class AppUser {
@Id private String userId;

// QUESTION 3: DO ALL CLASSES REQUIRE A KEY FIELD?
private Key<AppUser> key;

protected AppUser(){}
protected AppUser(User u){// GAE User object    
    this.userId = u.getUserId();
}

public String getId(){
    return userId;
}

public Key<AppUser> getKey(){
    // QUESTION 4: IS THIS THE CORRECT WAY TO RETURN THE KEY? 
    // WOULD THAT IMPLY I NEED TO EXPLICITLY ASSIGN A VALUE TO FIELD key?

    return this.key;

    // THE ALTERNATIVE WOULD BE TO CREATE A KEY 
AND RETURN IT RIGHT? (THEN I CAN EXCLUDE FIELD key?)
    // return Key.create(AppUser.class, userId);
}
}
4

1 回答 1

3

根据进一步的知识回答我自己的问题:

  1. 通常,如果需要父关系,一个 Key 就可以了。我不明白为什么需要另一个 Key 字段。
  2. 我认为没有一种正确的方法可以为@Parent Key 赋值。使用它似乎有效:

    this.parent = Key.create(instanceOfParent);

  3. 所有类都不需要关键字段。需要时使用。
  4. 没有一种正确的方法可以返回 Key,这两个示例都可以。
于 2012-12-07T15:24:32.797 回答