I am moving from Datanucleus to Objectify. How do I rewrite the following OneToMany
code for Objectify?
@Entity
public class Person{
…
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Dog> dogs = new HashSet<Dog>();
…
}
Right now to query Person and get all my dogs, I simply do
public Person findById(String uid) {
EntityManager mgr = getEntityManager();
try {
String jpql = "SELECT a FROM Person a WHERE a.uid = :uid";
TypedQuery<Person> q = mgr.createQuery(jpql, Person.class);
q.setParameter("uid", uid);
return q.getSingleResult();
} catch (Exception e) {// entityNotFoundException or NoResultException
return null;
} finally {
mgr.close();
}
}
And I can iterate through dogs as
Person owner = personDao.findById(id.getUid());
for (Dog dog : owner.getDogs()) {
//… do stuff
}
By the way, uid
is not annotated as @Id
so that it is not a key.
Basically, if you want an object A to "have many" object B's you have to make A have a field that holds a list of pointers (Keys) to the Bs. This is described on the oficial Objectify's documentation [1].
[1] https://github.com/objectify/objectify/wiki/Entities#one-to-many-relationships
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.