How to catch or handle OptimisticLockException?
bravefox Jun 14, 2012 12:14 AMI ran into a problem. I develop a test application on EJB3.1 (Jboss AS 7.1.1). The project has several entity and one stateless-bean. Entity`s have annotation @ Version. In the method of stateless-bean, I get an object. Then in parallel thread I increment a version of the object in the database to generate an exception.
Test bean:
@Stateless
public class TestBean implements ITestRemote, Serializable {
private static final long serialVersionUID = 1L;
@PersistenceContext(unitName = "datasource1")
private EntityManager _em;
public TestBean() {
}
public String findAndUpdate() {
User user = _em.find(User.class, 9L, LockModeType.OPTIMISTIC);
user.getPhone().setNumber("777555");
try {
_em.merge(user);
_em.flush();
} catch (OptimisticLockException e) {
return "exception";
}
return “complete”;
}
Exception:
10:16:55,336 WARN [com.arjuna.ats.arjuna] (EJB default - 2) ARJUNA012125: TwoPhaseCoordinator.beforeCompletion - failed for SynchronizationImple< 0:ffff0a0101b1:-1a2aaf4b:4fd955f1:1a, org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization@19993a7 >: org.hibernate.OptimisticLockException: Newer version [34] of entity [[org.test.entity.User#9]] found in database
at org.hibernate.action.internal.EntityVerifyVersionProcess.doBeforeTransactionCompletion(EntityVerifyVersionProcess.java:54) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:566) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.engine.spi.ActionQueue.beforeTransactionCompletion(ActionQueue.java:218) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:510) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.engine.transaction.synchronization.internal.SynchronizationCallbackCoordinatorImpl.beforeCompletion(SynchronizationCallbackCoordinatorImpl.java:113) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.engine.transaction.synchronization.internal.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:53) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:76)...
How do I catch this exception? Operation flush() does not help. Update is executed after the completion of the method.
I`m so sorry for my English. Thanks in advance.