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

前端 未结 4 1213
一整个雨季
一整个雨季 2021-02-14 12:22

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

相关标签:
4条回答
  • 2021-02-14 12:33

    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.

    0 讨论(0)
  • 2021-02-14 12:37

    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/

    0 讨论(0)
  • 2021-02-14 12:48

    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.

    0 讨论(0)
  • 2021-02-14 12:54

    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

    0 讨论(0)
提交回复
热议问题