Reputation: 740
I'm trying to implement a simple GAE service. Particularry I have the Student entity and Category entity. To each Student can be associated one or more Categories. How can I create this relationship using Objectify? THanks
Edit: This is my code. Is It valid?
@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);
}
}
Upvotes: 1
Views: 248
Reputation: 6717
I would suggest having a third entity with indexed references to both entities. That way, you could easily query for every student in a category, or for every category of a student.
@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;
/*...*/
}
We have a similar setup in our GAE applications, and it has served us well.
Upvotes: 0
Reputation: 80330
Create a muti-valued indexed field in Student
that holds all Category
IDs (or Keys):
@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
}
Indexed fields can be used in query filters, so you will be able to search for students that belong to certain category.
Upvotes: 1