Mingtao Sun Mingtao Sun - 2 months ago 13
Java Question

Merge an entity, change its id, merge again, cause "mapped to a primary key column in the database. Updates are not allowed" error

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. I rewrite my code to illustrate my problem in the simplest way.

User user = userManager.find(1);
userManager.merge(user);
System.out.println("User is managed? "+userManager.contains(user);
user.setId(2);
userManager.merge(user);


The above code is not in a transaction context. userManager is a stateless session bean with an EntityManager injected. When executed, the console prints:

User is managed? false

Exception [EclipseLink-7251] (Eclipse Persistence Services - 2.1.3.v20110304-r9073): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The attribute [id] of class [demo.model.User] is mapped to a primary key column in the database. Updates are not allowed.


The exception occurs at the second merge() invocation.

If I create a new user, sets its ID and merge it, it works:

User user = userManager.find(1);
userManager.merge(user);
System.out.println("User is managed? "+userManager.contains(user);
User newUser = new User();
newUser.setId(2);
userManager.merge(newUser);


So what is the difference between the first scenario and second one? According to the JPA specification, as long as the entity is in detached state, the merge should succeed, right?
(Assuming the entity with ID=2 exists)

Why the EclipseLink provider seems to be bothered by the fact that the user entity has been merged before?

Update: It seems to be an bug of EclipseLink. I have replaced the persistence provider from EclipseLink to Hibernate:

I change

<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>


to

<provider>org.hibernate.ejb.HibernatePersistence</provider>


No error has been thrown.

Answer

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.

Comments