gpt4 book ai didi

java - 坚持 GAE 后将子实体添加到父实体

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:00 29 4
gpt4 key购买 nike

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

我的问题是:如何将子对象添加到已持久化的父对象中?如果调用下面示例中的函数 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);
}

最佳答案

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

关于java - 坚持 GAE 后将子实体添加到父实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13616685/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com