Reputation: 944
I have an issue with my OneToMany relationships in my GAE JPA2 applicaiton.
I have two classes:
@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
}
And then I have a little testbed service where I am doing the following:
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();
I am confused as to why the list isn't being detached... I could understand it if my FetchType was LAZY, but it's not... It's set to EAGER.
Any ideas?
UPDATE I can reproduce the problem just as well by only using the following lines in my testbed service
String uuid; //hardcoded to match an existing uuid in the datastore
A a = A.getA(uuid)
a.getBList();
Upvotes: 1
Views: 106
Reputation: 19002
b
, you forgot to add it to the a
's list.EntityManager
s that have nothing in common. Try using the same em when saving A
and B
.Upvotes: 1