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

前端 未结 4 1218
一整个雨季
一整个雨季 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: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 cu = cb.createCriteriaUpdate(User.class);
    Root 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/

提交回复
热议问题