2012-12-04 54 views
3

我正在持续与Objectify湿我的脚。我想要分配父键的一些指导。我的具体问题全部大写。谢谢。 (样品模型下面包含APPUSER和视频的想法是像YouTube,用户创建一个属于他/她的影片。)Objectify如何分配值父密钥

@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

我想知道是否把'AppUser au = ofy().load().type(AppUser.class).filter(“userId”,u.getUserId())。first()。get() ;在视频构造函数中会使它很难测试?也许最好将AppUser传入视频构造函数。 –

回答

3

基础上,进一步的知识回答我的问题:

  1. 通常情况下,如果需要父母关系,一个密钥是好的。我不明白为什么会需要另一个关键字段。
  2. 我不认为有一个正确的方法为@Parent键赋值。使用这似乎工作:

    this.parent = Key.create(instanceOfParent);

  3. 所有的类都不需要关键字段。在需要时使用。
  4. 没有一个正确的方法来返回一个Key,这两个例子都可以工作。
相关问题