OneToMany 从 JPA/JDO 到 Objectify

OneToMany from JPA/JDO to Objectify

我正从 Datanucleus 转向 Objectify。如何为 Objectify 重写以下 OneToMany 代码?

@Entity
public class Person{
  …
  @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  private Set<Dog> dogs = new HashSet<Dog>();
  …
}

现在查询 Person 并获取我所有的狗,我只是这样做

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

我可以遍历狗

Person owner = personDao.findById(id.getUid());
for (Dog dog : owner.getDogs()) {
  //… do stuff
}

顺便说一下,uid 没有注释为 @Id,因此它不是键。

基本上,如果你想要一个对象 A 到 "have many" 对象 B,你必须让 A 有一个字段,其中包含指向 B 的指针(键)列表。这在 Objectify 的官方文档 [1].

中有描述

[1] https://github.com/objectify/objectify/wiki/Entities#one-to-many-relationships