我正在使用GAE JPA。我的关系如下:
DummyParent有n个用户,每个用户有n个项目。 DummyParent - >用户 - >项目
仅在用户和没有项目的情况下持久化DummyParent我的代码才有效。但是,拥有多层次的父母关系是行不通的。
@Entity
public class DummyParent{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@OneToMany(targetEntity=User.class, mappedBy="dummyP", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
private ArrayList<User> users;
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key key;
@ManyToOne(fetch=FetchType.LAZY)
private DummyParent dummyP;
private long id;
@OneToMany(targetEntity=Item.class, mappedBy="likedits", fetch=FetchType.LAZY, cascade = CascadeType.ALL)
public Set<Item> likeditemlist = new HashSet<Item>();
}
@Entity
public class Item {
public String name;
@ManyToOne(fetch=FetchType.LAZY)
private User likedits;
}
代码要坚持:
DummyParent dp = new DummyParent():
for(FbUser fu : fbuserlist) {
User user = new User();
user.likeditemlist.addAll(items);
user.setName(fu.getName());
dp.users.add(user);
// Excluded try catch here It is there in my code
}
em.persist(dp);
em.close();
在em.close();
上获得以下异常Caused by: com.google.appengine.datanucleus.EntityUtils$ChildWithWrongParentException: Detected attempt to establish User(no-id-yet) as the parent of DummyParent(1)/User(101)/Item(105) but the entity identified by DummyParent(1)/User(101)/Item(105) is already a child of DummyParent(1)/User(101). A parent cannot be established or changed once an object has been persisted.
at com.google.appengine.datanucleus.EntityUtils.extractChildKey(EntityUtils.java:941)
at com.google.appengine.datanucleus.StoreFieldManager.getDatastoreObjectForCollection(StoreFieldManager.java:967)
at com.google.appengine.datanucleus.StoreFieldManager.storeFieldInEntity(StoreFieldManager.java:394)
at com.google.appengine.datanucleus.StoreFieldManager.storeObjectField(StoreFieldManager.java:185)
at org.datanucleus.state.AbstractStateManager.providedObjectField(AbstractStateManager.java:1447)