Reputation: 53
I have a parent entity client. This client can come to the website and create appointments. This means that the appointments are created on another time then the client objects.
My question is: how do you add a child object to a parent object that is already persisted? If the function addData1() in the example below is called, an Appointment table is created and an entry is added. When function addData2() is called this doesn't happen.
Isn't it so that when you update a persisted object after closing the entitymanager this is also updated in the table?
@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);
}
Upvotes: 1
Views: 275
Reputation: 176
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 function works because you persist all the object.
// 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)
}
This function doesn't because you try to persist an object with detached entity
You should get the exception like this:
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.test.Appointment
if you want to avoid this exception, you can try this approach:
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();
}
BTW, try to void using name as Id
Upvotes: 1