EntityManager throws OptimisticLockException when trying to delete a locked object in one transaction

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 execute this 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 someone explain to me why this is?

+3


source to share


2 answers


I assume that you added the @Version

-annotated column after you already have some records in the database, so some null values ​​were generated for the already existing records. Now hibernate cannot compare versions.



I would try to set the version column to 1 for all objects with a zero version.

+1


source


I think this error is due to the fact that I am trying to delete a record that has a lock on it. When trying to delete this line, install the version null

, but the version in the database is still the same. It seems that the hibernate kernel perceives the value null

as unreliable for this kind of operation.

If I need to perform such an operation, I must first lock the lock on this entity.



Anyone who knows better about this should clarify this issue.

+1


source







All Articles