我有一个父实体客户。该客户可以访问网站并创建约会。这意味着约会是在另一个时间创建的,然后是客户端对象。
我的问题是:如何将子对象添加到已经持久化的父对象中?如果调用下面示例中的函数 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);
}