客观化和关系

时间:2013-11-20 10:40:09

标签: java google-app-engine google-cloud-datastore objectify

我正在尝试实施简单的GAE服务。特别是我有学生实体和类别实体。每个学生可以关联一个或多个类别。如何使用Objectify创建这种关系?感谢

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

@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);
    }
}

2 个答案:

答案 0 :(得分: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
}

索引字段可用于查询过滤器,因此您可以搜索属于特定类别的学生。

答案 1 :(得分: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<?>

相关问题