Optimistic Lock problem occurring
Environment
- Red Hat JBoss Fuse
- 6.1.0
Issue
- Optimistic Lock problem occurring when using OpenJPA
- When trying to flush an OpenJPA EntityManager the following exception is thrown:
<openjpa-2.3.0-r422266:1540826 fatal store error> org.apache.openjpa.persistence.OptimisticLockException: Optimistic locking errors were detected when flushing to the data store. The following objects may have been concurrently modified in another transaction: [com.example.domain.ModelClass-2016001]
at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2359)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2207)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2105)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1876)
at org.apache.openjpa.kernel.DelegatingBroker.flush(DelegatingBroker.java:1045)
at org.apache.openjpa.persistence.EntityManagerImpl.flush(EntityManagerImpl.java:663)
at org.apache.aries.jpa.container.impl.EntityManagerWrapper.flush(EntityManagerWrapper.java:117)
at org.apache.aries.jpa.container.context.transaction.impl.JTAEntityManager.flush(JTAEntityManager.java:218)
...
Resolution
When using JPA, you should refresh the object to be saved first, using entityManager.refresh(ModelClass)
, then update it and only then merge and flush it.
For example:
TypedQuery query = entityManager.createNamedQuery("ModelClass.getId", ModelClass.class);
query.setParameter("id", 10);
ModelClass modelClass = (ModelClass) query.getSingleResult();
entityManager.refresh(modelClass);
modelClass.setTimestamp(new Timestamp(System.currentTimeMillis()));
entityManager.merge(modelCLass);
entityManager.flush();
This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.
Comments