我的GAE JPA2应用程序中的OneToMany关系存在问题。

我有两节课:

@Entity(name="A")
public class A {
    @Id
    private String uuid;
    @OneToMany(mappedBy="a")
    private List<B> bList;

    public A() {
        //set uuid
        bList = new ArrayList<B>();
    }

    public List<B> getBList() {
        return bList;
    }

    //Other getters and setters

    public static A create() {
        EntityManager em = //get entity manager
        A a = new A();
        try {
            em.persist(a);
        } catch(Exception e) {
            return null;
        } finally {
            em.close();
        }

        return a;
    }

    public static A getA(String uuid) {

        EntityManager em = // get EM
        A a = em.find(A.class, uuid);
        em.close();
        return a;
    }

    public void update() {
        EntityManager em = // create EM
        try {
            em.merge(this);
        } finally {
            em.close();
        }
    }
}

@Entity (name="B")
public class B
{
    //id stuff

    @ManyToOne(fetch=FetchType.EAGER)
    A a;

    public B(A a) {
        //create key using 'a' as parent
        this.a = a;
    }

    public static B create(A a) {
        EntityManager em = //create EM
        B b = new B(a);
        try {
          em.persist(b);
        } catch (Exception e) {
          return null;
        } finally {
          em.close();
        }
        return b;
    }

    //get and update methods similar to the A class above

}


然后,我有一个小测试平台服务,我正在执行以下操作:

String uuid; //hardcoded to match an existing uuid in the datastore
A a = A.getA(uuid);
B b = B.create(a);
a.getBList().add(b);
a.update();


我对为什么列表未分离感到困惑...如果我的FetchType为LAZY,我可以理解它,但事实并非如此……它设置为EAGER。

有任何想法吗?

更新
我也可以通过仅在测试平台服务中使用以下几行来重现该问题

String uuid; //hardcoded to match an existing uuid in the datastore
A a = A.getA(uuid)
a.getBList();

最佳答案

保留b之前,您忘记将其添加到a的列表中。
另一个问题可能是您使用了两个没有共同之处的EntityManager。保存AB时,请尝试使用相同的em。

10-04 17:59