EntityManager throws OptimisticLockException when try to delete locked entity in same transaction

丶灬走出姿态 提交于 2019-12-10 17:48:23

问题


Here is my code:



EntityManager em = JPAUtil.createEntityManager();

   try {

     EntityTransaction tx = em.getTransaction();

     try {

           //do some stuff here
           tx.begin();
           List es = em.createNamedQuery("getMyEntities", MyEntity.class).getResultList();

           for (MyEntity e : es) {
               em.lock(e, LockModeType.OPTIMISTIC);
           }

           if (es.size() != 0) {

               em.remove(es.get(0));

           }

        tx.commit

     } finally {

        if (tx.isActive()) {
            tx.rollback();
        }

     }

   } finally {

      em.close();

   }

When I'm executing that code I get :

...


..........
Caused by: javax.persistence.OptimisticLockException: Newer version [null] of entity [[MyEntity#63]] found in database
    at org.hibernate.ejb.AbstractEntityManagerImpl.wrapLockException(AbstractEntityManagerImpl.java:1427)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1324)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:80)
    ... 23 more

Can anybody explain me why that?


回答1:


I suppose that you have added the @Version-annotated column after you already had some entries in database, so that some null-values were created for the already-existing records. Now hibernate can't compare the versions.

I would try to set the version column to 1 for all null-versioned entities.




回答2:


I think this error is thrown due to the fact that I try to delete a record that has a lock on it. Trying to delete this row, will set the version to null, but the version in the database still remains set to former number. It seems that hibernate core perceive a null value to be not reliable for this kind of operation.

If I have to do this kind of operation, I have to release the lock first on this entity.

Anyone with better knowledge on it has to clarify that issue.



来源:https://stackoverflow.com/questions/14455202/entitymanager-throws-optimisticlockexception-when-try-to-delete-locked-entity-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!