Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top