I have a JPA program where EclipseLink is a containment provider. When I merge a user object, change its identifier and try to merge the same user instance again, an error occurs. I am rewriting my code to illustrate my problem in the easiest 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 the context of a transaction. userManager is a non-bean session with EntityManager entered. 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.
An exception occurs in the second call to merge ().
If I create a new user, sets his identifier and combines 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 the second? According to the JPA specification, as long as the object is in a detached state, the merge must be successful, right? (Assuming an object with ID = 2 exists)
Why does the EclipseLink provider seem concerned about the fact that the user object was merged before?
Update: this seems to be an EclipseLink error. I replaced the persistence provider from EclipseLink to Hibernate:
I am changing
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
to
<provider>org.hibernate.ejb.HibernatePersistence</provider>
No error has been selected.
Mingtao sun
source share