我坚持不懈地和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);
}
}
答案 0 :(得分:3)
基于进一步的知识回答我自己的问题:
我认为没有一种正确的方法可以为@Parent Key赋值。使用它似乎有效:
this.parent = Key.create(instanceOfParent);