I have an Entity
with a bidirectional ManyToMany
relationship (on the same entity) marked as CascadeType.ALL
.
Here is how it looks for the Contact
entity:
@ManyToMany(cascade= CascadeType.ALL)
private List<Contact> parentContacts = new ArrayList<Contact>();
@ManyToMany(cascade= CascadeType.ALL, mappedBy="parentContacts")
private List<Contact> childContacts = new ArrayList<Contact>();
I have a method on the server side supposed to do save this entity:
public AltContact saveContact(EntityManager em, Contact contact, List<Contact> childs) {
for (Contact c : childs) {
contact.getChildContacts().add(c);
c.getParentContacts().add(contact);
}
if (contact.getId() == null) {
em.persist(contact);
} else {
contact = em.merge(contact);
}
return contact;
}
It works great if the contact
or any entities of the childs
list are not persisted. But sometimes i will need to use the saveContact
method with already persisted entities, and when i try to do this, it seems like JPA try to persist all the entities of the relationship and then will raise the exception:
Internal Exception: java.sql.SQLIntegrityConstraintViolationException
Indeed, it'll try to repersist and already persisted entity, so the unicity of the ID field of Contact
will be violated.
How can active this? What's wrong with my approach?
How can i make Eclipselink/JPA does not try to persist entities that are part of the relationship and that are already persisted?