JPA: Merge @OneToMany Duplicate entry error
I'm alwways getting the following error:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '2-1' for key 'PRIMARY'
Error Code: 1062
Call: INSERT INTO ENTITY_ENTITY (relationships_ID, Entity_ID) VALUES (?, ?)
bind => [1, 2]
Query: DataModifyQuery(sql="INSERT INTO ENTITY_ENTITY (relationships_ID, Entity_ID) VALUES (?, ?)")
My classes look like:
@javax.persistence.Entity
public class Entity {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
protected Long id;
@Column(nullable=false, updatable=false)
protected String name;
@OneToMany(cascade=CascadeType.MERGE)
protected Collection<Entity> relationships = new ArrayList<Entity>();
}
One instance of this class can reference other instances of the same type (self-referencing). Now, while creating one instance which references another, everything works fine. But the problem is, when such an (detached - I'm not quite sure, because the instance is edited via a Facelets form) instance is updated, i.e. the name, then by executing the EntityManager merge operation the exception - as mentioned above - is thrown.
EDIT:
1. Create one instance of Entity (i.e. E1). 2. Persist E1 via em.persist(E1). 3. Later, create another instance of Entity (E2) which refreneces E1 via the property relationships. 4. And persist E2: em.persist(E2).--- Until now everything works fine.
- Load to browse all persisted Entity instances and choose E2 for editing (via开发者_开发问答 a Web interface Facelet).
- Change i.e. the name of E2.
- To save the changes: Call em.merge(E2).
---Now the Exception is thrown!
END EDIT
What's wrong with my code? Please, help me!!!
It seems the way you are detaching/merging your objects is somehow corrupting the object to have a two references to the same Entity, or to think a reference is new when it was existing. This is causing the INSERT into the OneToMany join table that is a duplicate and is raising the constraint violation.
Trying debugging or checking the state of the collection at every stage, does it get a duplicate instance added to it?
Possibly it could have something to do with caching or change tracking. You could try turning off the shared cache, or refreshing the object, or disabling weaving.
http://wiki.eclipse.org/EclipseLink/FAQ/How_to_disable_the_shared_cache%3F
http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching#How_to_refresh_the_cache
http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_%28ELUG%29#How_to_Disable_Weaving_Using_EclipseLink_Persistence_Unit_Properties
精彩评论