Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)


I have a java project that runs on a webserver. I always hit this exception.

I read some documentation and found that pessimistic locking (or optimistic, but I read that pessimistic is better) is the best way to prevent this exception.

But I couldn't find any clear example that explains how to use it.

My method is like:

    public void test(Email email, String subject) {
        getEmailById(String id);


  • Email is a Hibernate class (it will be a table in the database)
  • getEmailById(String id) is a function that returns an email (this method is not annotated with @Transactional)
  • updateEmail(email): is a method that updates the email.

Note: I use Hibernate for save, update & so on (example:

The exception:

ERROR 2011-12-21 15:29:24,910 Could not synchronize database state with session [myScheduler-1]
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [email#21]
    at org.hibernate.persister.entity.AbstractEntityPersister.check(
    at org.hibernate.persister.entity.AbstractEntityPersister.update(
    at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(
    at org.hibernate.persister.entity.AbstractEntityPersister.update(
    at org.hibernate.action.EntityUpdateAction.execute(
    at org.hibernate.engine.ActionQueue.execute(
    at org.hibernate.engine.ActionQueue.executeActions(
    at org.hibernate.engine.ActionQueue.executeActions(
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(
    at org.hibernate.impl.SessionImpl.flush(
    at org.hibernate.impl.SessionImpl.managedFlush(
    at org.hibernate.transaction.JDBCTransaction.commit(
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(
    at $Proxy130.generateEmail(Unknown Source)
    at com.admtel.appserver.tasks.EmailSender$$FastClassByCGLIB$$ea0d4fc2.invoke(<generated>)
    at net.sf.cglib.proxy.MethodProxy.invoke(
    at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(
    at com.admtel.appserver.tasks.EmailNotificationSender$$EnhancerByCGLIB$$<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(
    at java.lang.reflect.Method.invoke(
    at org.springframework.util.MethodInvoker.invoke(
    at java.util.concurrent.Executors$
    at java.util.concurrent.FutureTask$Sync.innerRunAndReset(
    at java.util.concurrent.FutureTask.runAndReset(
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(
    at java.util.concurrent.ScheduledThreadPoolExecutor$
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(
    at java.util.concurrent.ThreadPoolExecutor$
ERROR 2011-12-21 15:29:24,915 [ exception thrown < > exception message Object of class [Email] with identifier [211]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [Email#21] with params ] [myScheduler-1]
org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Object of class [Email] with identifier [21]: optimistic locking failed; nested exception is 

This question is tagged with java hibernate spring amazon-web-services pessimistic-locking

~ Asked on 2011-12-27 14:25:15

The Best Answer is


Pessimistic locking is generally not recommended and it's very costly in terms of performance on database side. The problem that you have mentioned (the code part) a few things are not clear such as:

  • If your code is being accessed by multiple threads at the same time.
  • How are you creating session object (not sure if you are using Spring)?

Hibernate Session objects are NOT thread-safe. So if there are multiple threads accessing the same session and trying to update the same database entity, your code can potentially end up in an error situation like this.

So what happens here is that more than one thread tries to update the same entity, one thread succeeds and when the next thread goes to commit the data, it sees that its already been modified and ends up throwing StaleObjectStateException.


There is a way to use Pessimistic Locking in Hibernate. Check out this link. But there seems to be some issue with this mechanism. I came across posting a bug in hibernate (HHH-5275), however. The scenario mentioned in the bug is as follows:

Two threads are reading the same database record; one of those threads should use pessimistic locking thereby blocking the other thread. But both threads can read the database record causing the test to fail.

This is very close to what you are facing. Please try this if this does not work, the only way I can think of is using Native SQL queries where you can achieve pessimistic locking in postgres database with SELECT FOR UPDATE query.

~ Answered on 2011-12-27 14:58:53


I know this is an old question, but some of us are still hitting it and look at the sky wondering how. Here is one kind of issue that I faced.

We have a queue manager that polls data and gives it to handlers for processing. To avoid picking up the same events again, the queue manager locks the record in the database with a LOCKED state.

    void poll() {
        record = dao.getLockedEntity();

this method wasn't transactional but dao.getLockedEntity() was transactional with REQUIRED.

All good and on the road, after few months in production, it failed with an optimistic locking exception.

After lots of debugging and checking in details we could find out that some one has changed the code like this:

    @Transactional(propagation=Propagation.REQUIRED, readOnly=false)
    void poll() {
        record = dao.getLockedEntity();

So the record was queued even before the transaction in dao.getLockedEntity() gets committed (it uses the same transaction of poll method) and the object was changed underneath by the handlers (different threads) by the time the poll() method transaction gets committed.

We fixed the issue and it looks good now.

I thought of sharing it because optimistic lock exceptions can be confusing and are difficult to debug. Someone might get benefited from my experience.

Regards, Lyju

~ Answered on 2013-09-27 01:41:22

Most Viewed Questions: