Hibernate | javax.persistence.OptimisticLockException: Row was updated or deleted by another transaction

Author - Webner

You may face following exception while trying to update data in a database table using hibernate:

javax.persistence.OptimisticLockException : Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.abc.pkg.db.entities.customer.CustomerOfferScheduledTask#2504849]

The reason is optimistic lock is applied on the database when we commit data to the database table. Any database object that has to be updated or deleted is checked for its latest version before doing final operation. Above exception is thrown if it was found out that an update was being performed on an old version of a database object, for which another update has already been committed by another transaction.

There are couple of solutions for this problem:

1. Just before updating the object check of it is in the cache memory or not. If it is there refresh it before update:

if (helper.getEntityManager().contains(entity bean object)
{
 helper.getEntityManager().refresh(entity bean object);
}
 update(pojo object);

2. Load the object from the database again before updating:

fromDatabase= getEntityManager().load(ClassName.class,2);
fromDatabase.setAmount(newAmount);
update(fromDatabase);

Use everything within database transactions.

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *