1

我正在使用 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)
4

0 回答 0