如何在jboss中处理JPA/hibernate中的OptimisticLockException?
我正在使用JPA处理JBOSS中的实体。在各种事务中,一个实体将由多个线程更新。我在实体中添加了@Version属性,并且在更新实体之前,我获得了OptimisticLock。如果事务失败,我无法处理异常并重试 实体为如何在jboss中处理JPA/hibernate中的OptimisticLockException?,hibernate,jpa,jboss7.x,Hibernate,Jpa,Jboss7.x,我正在使用JPA处理JBOSS中的实体。在各种事务中,一个实体将由多个线程更新。我在实体中添加了@Version属性,并且在更新实体之前,我获得了OptimisticLock。如果事务失败,我无法处理异常并重试 实体为 @Entity public class DataEntity { @Id int id; long count; @Version int versionAttribute; ....
@Entity
public class DataEntity
{
@Id
int id;
long count;
@Version
int versionAttribute;
....
....
更新实体的代码为
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateEntity()
{
DataEntity d=entityManager.find(DataEntity.class,0,LockModeType.OPTIMISTIC);
d.setCount(d.getCount()+1);
}
如您所见,updateEntity()方法使用TransactionAttributeType.REQUIRES\u NEW来创建新事务。这里的事务是容器管理的。因此,请帮助我在引发OptimisticLockingException时重试
在哪里处理异常/在哪里写入重试逻辑?如何处理事务边界外的事务
public class SafeHandleInterceptor implements MethodInterceptor {
private final Logger logger = LoggerFactory.getLogger();
private int maxRetryCount = 3;
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
int retryCount = 0;
while (true) {
try {
ReflectiveMethodInvocation inv = (ReflectiveMethodInvocation) invocation;
// clone before proceed, each inv could be proceed only once
MethodInvocation anotherInvocation = inv.invocableClone();
return anotherInvocation.proceed();
} catch (OptimisticException e) {
if (retryCount++ >= maxRetryCount) {
throw e;
} else {
logger.info("retry for exception:" + e.getMessage(), e);
continue;
}
}
}
}
}
编织:
<bean id="your original transactional bean name" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="reference to your original transactional bean" />
<property name="proxyInterfaces"
value="your interface" />
<property name="interceptorNames" value="safeHandleInterceptor" />
</bean>