1

我有一个父实体客户。该客户可以访问网站并创建约会。这意味着约会是在另一个时间创建的,然后是客户端对象。

我的问题是:如何将子对象添加到已经持久化的父对象中?如果调用下面示例中的函数 addData1(),则会创建一个约会表并添加一个条目。当函数 addData2() 被调用时,这不会发生。

不是这样当您在关闭实体管理器后更新持久对象时,这也会在表中更新吗?

@Entity
public class Client{
    @Id
    private String name;
    @OneToMany(cascade = CascadeType.ALL)
    private Set<Appointment> appointments;
}

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

// This works
public function addData1(){
    EntityManager em = EMF.get().createEntityManager();
    Client client = new Client(name);
    for(Appointment a  : newAppointments)
        client.addAppointment(a);
    em.persist(client);
    em.close();
}

// This doesn't work.
public function addData2(){
    EntityManager em = EMF.get().createEntityManager();
    Client client = new Client(name);
    em.persist(client);
    em.close();
    for(Appointment a  : newAppointments)
        client.addAppointment(a);
}
4

1 回答 1

1
public function addData1(){
    EntityManager em = EMF.get().createEntityManager();
    Client client = new Client(name);
    for(Appointment a  : newAppointments)
        client.addAppointment(a);
    em.persist(client);
    em.close();
}

此功能有效,因为您保留了所有对象。

// This doesn't work.
public function addData2(){
    EntityManager em = EMF.get().createEntityManager();
    Client client = new Client(name);
    em.persist(client);
    em.close();    <--- You persist client with no appointment
    for(Appointment a  : newAppointments)
        client.addAppointment(a);   <-- those entitys are detached entity ( not persisted)
}

此功能不是因为您尝试使用分离实体来持久化对象

你应该得到这样的异常:

Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.test.Appointment

如果你想避免这个异常,你可以试试这个方法:

public void addData2(List<Appointment> newAppointments){
    Client client = new Client();
    client.setName("name1");
    entityManager.persist(client);
    for(Appointment a  : newAppointments)
        client.addAppointment(a);
    entityManager.merge(client);
    entityManager.close();
}

顺便说一句,尝试使用名称作为 Id 无效

于 2012-11-29T02:23:47.043 回答