I have a JPA program where EclipseLink is the Persistence provider. When I merge an user entity, change its ID, and try to merge the same user instance again, an error is thrown
The reason is that the Id
may be inserted/defined - as you do in your second example, but not changed/updated - as you try in your first example. The JPA provider tries to reflect the change in the database and fails.
JPA 2 spec §2.4 says
The application must not change the value of the primary key. The behavior is undefined if this occurs.
This answer is 4 years late but anyway.
You can update it by executing regular update queries using SQL or JPQL or Criteria API. I find the last one is the best.
Here is a code example that can do the trick. I have tried it in a similar situation and it works fine with EclipseLink.
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<User> cu = cb.createCriteriaUpdate(User.class);
Root<User> c = cu.from(User.class);
cu.set(User_.id, newId).where( cb.equal(c.get(User_.id), oldId) );
em.createQuery(cu).executeUpdate();
Instead of User_.id you can pass the name of the field as a String e.g. "id".
Another example http://www.thoughts-on-java.org/criteria-updatedelete-easy-way-to/
It seems to be an bug of EclipseLink. I have changed the persistence provider from EclipseLink to Hibernate:
from
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
to
<provider>org.hibernate.ejb.HibernatePersistence</provider>
No error has been thrown.
The version of EclipseLink is 2.3.2. (which is shipped with the latest Glassfish application server 3.1.2).
The version of hibernate is, as of now the latest, 4.1.7.
Try <property name="eclipselink.weaving.internal" value="false"/>
in persistence.xml as per
http://blogs.nologin.es/rickyepoderi/index.php?/archives/95-Weaving-Problem-in-EclipseLink.html