Как создать объект в определенной группе объектов с помощью JPA? (Google AppEngine Java) - PullRequest
2 голосов
/ 05 февраля 2011

Я хочу использовать транзакции в 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 Ответ

2 голосов
/ 06 февраля 2011

Кей ... просто маленькая ошибка в моей первой попытке.

Это должно работать:

@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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...