2013-11-20 45 views
1

我正在尝试实现一个简单的GAE服务。特殊情况我有学生实体和类别实体。对每个学生可以关联一个或多个类别。我如何使用Objectify创建这种关系? THanks物化与关系

编辑:这是我的代码。它有效吗?

@Entity 
public class Studente { 
    static long nextID = 17; 

    public static Key<Studente> key(long id) { 
     return Key.create(Studente.class, id); 
    } 

    List<Key<Categoria>> categorie; 

    public Studente() {} 

    @Id Long id; 
    @Index String nome; 
    @Index String cognome; 
    @Index String username; 
    @Index String password; 

    public Studente(String nome, String cognome, String username, String password) { 
     this.nome=nome; 
     this.cognome=cognome; 
     this.username=username; 
     this.password=password; 
     categorie = new ArrayList<Key<Categoria>>(); 
    } 

    public static long getNextID() { 
     return nextID; 
    } 

    public static void setNextID(long nextID) { 
     Studente.nextID = nextID; 
    } 

    public List<Key<Categoria>> getCategorie() { 
     return categorie; 
    } 

    public void setCategorie(List<Key<Categoria>> categorie) { 
     this.categorie = categorie; 
    } 

    public void addCategoria(Key<Categoria> k){ 
     categorie.add(k); 
    } 
} 

回答

0

我会建议有一个第三个实体与两个实体索引引用。这样,您就可以轻松查询某个类别中的每个学生或每个学生的类别。

@Entity 
public class Student { /*...*/ } 

@Entity 
public class Category { /*...*/ } 

@Entity 
public class StudentCategory { 
    @Id 
    private Long id; 

    @Index 
    private Ref<Student> student; 

    @Index 
    private Ref<Category> category; 

    /*...*/ 
} 

我们已经在我们GAE应用类似的设置,并且它一直运作良好。

See documentation of Ref<?>

+0

在答案的同时,我做了一个示例工作代码。你能检查我的问题吗? – Frank

+0

你的解决方案应该可以工作,但它不是很方便。 'Ref'比'Key'更方便(参见我链接的文档)。此外,如果列表中没有“@ Index”注释,您将无法查询具有某个类别的学生。你只能说出一个不同的学生有什么类别。抛开一切,你的解决方案应该工作,是的。 –

+0

您可以在没有中介'StudentCategory'实体的情况下,通过使用每个'Student'和'Category'中的参考列表来做同样的事情。这将为您节省额外的代码和成本。 –

1

Student创建穆蒂值索引的字段包含所有Category ID(或键):

@Entity 
public class Category { 
    @Id 
    public Long id; // auto-generated Id of the Category 

} 

@Entity 
public class Student { 
    @Id 
    public Long id; // auto-generated Id of the Student 

    @Index 
    public List<Long> categories; // put Category Ids into this list 
} 

索引字段可以在查询过滤器使用,所以你就可以搜索属于某一类别的学生。

+0

在答案的同时,我做了一个示例工作代码。你能检查我的问题吗? – Frank