如何使用JPA在特定实体组中创建对象? (谷歌AppEngine Java)

时间:2011-02-05 19:10:54

标签: java google-app-engine jpa transactions

我想在GAE-J和JPA中使用交易。

没有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.

听起来有点回到前面...... 我是个笨蛋吗?或者有一种简单的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

kay ...我的第一次尝试只是一个小错误。

这应该有效:

@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;
}