Reputation: 86627
What is the proper way of persisting a Parent object that should get a child object attached? The child object may already exist in DB, and may live on its own.
@Entity
class Parent {
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
Child child;
}
usage:
Parent p = new Parent("parent");
Child c = new Child("test");
Child child = em.find(c);
if (child == null) {
child = c;
}
p.setChild(child);
em.persist(p); //works only if child does not come from db, eg is transient
//em.merge(p); //works always, but is this intended to save a transient parent with persisted child this way?
Upvotes: 1
Views: 856
Reputation: 2053
Well entityManager.merge() is meant to save the changes of a detached object into the DB. The merge call does not update the object directly into the DB. It merges the changes into the Persistence Context and it is flushed upon the transaction commit.
Persist on the other hand should normally be called only on New objects.
Read through this very well explained documentation
Another important point to note here is also that the merge method has a returntype where it returns the entity back to you. so it is sort of like an update, though the entity which was passed in was detached and now the entity which is returned back is attached to the persistence context. Persist doesnt have a return type and is sort of like a create
Upvotes: 1