2011-02-05 31 views
2

我想在JPE中使用GAE-J中的事務。如何使用JPA在特定實體組中創建對象? (Google AppEngine Java)

沒有JPA它應該是:

Entity child= new Entity("Child", "ParentKey"); 

,但如何使用JPA辦呢?

@Entity 
public class Parent{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Key id; 
    private String text; 
} 

@Entity 
public class Child{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Key id; 
    private Parent parent; 
    private String text; 
} 

嘗試...

Parent parent = new Parent(); 
em.persist(parent); 
em.refresh(parent); 

Child child = new Child(); 
child.setParent(parent); 
em.persist(child); 

這不起作用:

org.datanucleus.store.appengine.DatastoreRelationFieldManager$ChildWithoutParentException: 
Detected attempt to establish Child(130007) as the parent of Parent(132001) but the entity identified by Child(132001) has already been persisted without a parent. A parent cannot be established or changed once an object has been persisted. 

這聽起來有點後到前... 我是一個傻瓜?還是有一個簡單的方法?

謝謝!

回答

2

凱...我的第一次嘗試只是一個小錯誤。

這應該工作:

@Entity 
public class Parent{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Key id; 
    private String text; 
    @OneToMany(targetEntity=Child.class, mappedBy="parent", fetch=FetchType.LAZY) 
    private Set<Child> children = new HashSet<Child>(); 
} 

@Entity 
public class Child{ 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Key id; 
    @ManyToOne(fetch=FetchType.LAZY, targetEntity=Parent.class) 
    private Parent parent; 
    private String text; 
} 
+0

這2類導致增強的錯誤我。 谷歌AppEngine上增強:顯示java.lang.NullPointerException 谷歌AppEngine上增強:通過在引起org.datanucleus.api.jpa.metadata.JPAAnnotationReader.newMetaDataForMember(JPAAnnotationReader.java:1995) 谷歌AppEngine上增強:在org.datanucleus.api .jpa.metadata.JPAAnnotationReader.processMemberAnnotations(JPAAnnotationReader.java:1126) – Boris 2013-02-09 10:04:37

相關問題