-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: OptimisticLockException during saveOrUpdate
PostPosted: Sun Nov 13, 2016 8:33 pm 
Newbie

Joined: Tue Nov 08, 2016 1:54 am
Posts: 14
I get
Code:
Caused by: javax.persistence.OptimisticLockException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

Exception when I flushing the session.

Code:
public void saveOrUpdate(T entity) {
      Session session = null;
      try {
         session = getSession();
         session.clear();
         session.saveOrUpdate(entity);
         session.flush();   //Gives issue--<
      }  catch (HibernateException ex) {
         log.error("Error when save or update." + entity.getCode(), ex);
      }
   }


I use container managed session. Hibernate V 5.2.1 and wildfly 10.0.1.
What I'm doing wrong here?

Error stack;

Code:
Caused by: javax.persistence.OptimisticLockException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
        at org.hibernate.internal.ExceptionConverterImpl.wrapStaleStateException(ExceptionConverterImpl.java:212)
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:86)
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
        at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
        at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1403)
        at com.cdi.crud.infra.Crud.saveOrUpdate(Crud.java:610)
        at com.cdi.crud.infra.CrudService.insertOrUpdate(CrudService.java:85)
        at com.xx.lob2.service.autogen.TankObservationService.insertOrUpdate(TankObservationService.java:444)
        at sun.reflect.GeneratedMethodAccessor301.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
        at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:82)
        at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:93)
        at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:437)
        at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
        at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:83)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ee.concurrent.ConcurrentContextInterceptor.processInvocation(ConcurrentContextInterceptor.java:45)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
        at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:52)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
        at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:340)
        at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:254)
        ... 181 more
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
        at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:67)
        at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:54)
        at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:46)
        at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3119)


Top
 Profile  
 
 Post subject: Re: javax.persistence.OptimisticLockException
PostPosted: Mon Nov 14, 2016 1:24 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
Maybe the entity was modified by some other concurrent transaction.

Use merge instead of saveOrUpdate.


Top
 Profile  
 
 Post subject: Re: javax.persistence.OptimisticLockException
PostPosted: Mon Nov 14, 2016 1:29 am 
Newbie

Joined: Tue Nov 08, 2016 1:54 am
Posts: 14
I do merge before calling saveOrUpdate


Code:
@TransactionAttribute(TransactionAttributeType.REQUIRED)
   public void insertOrUpdate(T entity) {
      if (entity == null) {
         throw new CustomException("Entity cannot be null");
      }
      try {
         List<T> resultList = null;
         if (entity.getCode() != null && entity.getId() ==null) {
            resultList = crud().criteria(crud().eq("code", entity.getCode()).getCriteria()).list();
         }
         if (entity.getId() != null) {
            resultList = crud().criteria(crud().eq("id", entity.getId()).getCriteria()).list();
         }
         if (resultList != null && !resultList.isEmpty()) {
            LobEntity entity2 = (LobEntity) resultList.get(0);
            entity.setId(entity2.getId());
            ((LobEntity) entity).setVersion(entity2.getVersion());
            crud().merge((T) entity);
         } else {
            crud().save(entity);
         }
      } catch (OptimisticLockException e) {
         crud().saveOrUpdate(entity);   //This gives issue, Merge throws Locking exception in this case
      } catch (Exception e) {
         log.error("Save or Update fails, ", e);
      }
   }



My merge code is like;
Code:
   public void merge(T entity) {
      Session session = null;

      try {
         session = getSession();
         session.clear();
         session.merge(entity);
         session.flush();
      } catch (HibernateException e) {
         log.error("Error when merge." + entity.getCode(), e);
      }
   
   }

vlad wrote:
Maybe the entity was modified by some other concurrent transaction.

Use merge instead of saveOrUpdate.


Top
 Profile  
 
 Post subject: Re: javax.persistence.OptimisticLockException
PostPosted: Mon Nov 14, 2016 1:36 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
This is where you got it all wrong:

Code:
} catch (OptimisticLockException e) {
    crud().saveOrUpdate(entity);   //This gives issue, Merge throws Locking exception in this case
}


Why do you try to saveOrUpdate when you get an OptimisticLockException?

Once you get an exception, you need to close the EntityManager and retry from a new Persistence Context.
Check out the Hibernate Session Javadocs:

Code:
If the Session throws an exception, the transaction must be rolled back and the session discarded.
The internal state of the Session might not be consistent with the database afterQuery the exception occurs.


The whole point of OptimisticLockingException is to protect you against lost updates. If you are sure that you can safely retry without risking an OptimisticLockingException , you can use this automatic retry mechanism.


Top
 Profile  
 
 Post subject: Re: javax.persistence.OptimisticLockException
PostPosted: Mon Nov 14, 2016 1:41 am 
Newbie

Joined: Tue Nov 08, 2016 1:54 am
Posts: 14
Can I close the entitymanager in Containermanaged transaction? I think, I should not.
In this case how should I proceed? Send the exception to the caller?

vlad wrote:
This is where you got it all wrong:

Code:
} catch (OptimisticLockException e) {
    crud().saveOrUpdate(entity);   //This gives issue, Merge throws Locking exception in this case
}


Why do you try to saveOrUpdate when you get an OptimisticLockException?

Once you get an exception, you need to close the EntityManager and retry from a new Persistence Context.
Check out the Hibernate Session Javadocs:

Code:
If the Session throws an exception, the transaction must be rolled back and the session discarded.
The internal state of the Session might not be consistent with the database afterQuery the exception occurs.


The whole point of OptimisticLockingException is to protect you against lost updates. If you are sure that you can safely retry without risking an OptimisticLockingException , you can use this automatic retry mechanism.


Top
 Profile  
 
 Post subject: Re: OptimisticLockException during saveOrUpdate
PostPosted: Mon Nov 14, 2016 1:44 am 
Hibernate Team
Hibernate Team

Joined: Thu Sep 11, 2014 2:50 am
Posts: 1628
Location: Romania
There's no reason why you should close the EntityManager because this is a Resource that's supposed to be managed by Wildfly.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.