从休眠乐观锁定异常中恢复 [英] Recovering from hibernate optimistic locking exception
问题描述
我有一个像这样的方法:
I have a method like this:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void doSomeWork(){
Entity = entity = dao.loadEntity();
// do some related work
...
try {
dao.saveEntity(entity);
}
catch(StaleObjectStateException sose){
dao.flush(entity);
doSomeWork();
}
}
我期望通过使用REQUIRES_NEW事务传播和所示的递归,StaleObjectStateException最终将被清除,但事实并非如此.
I was expecting that by using REQUIRES_NEW transaction propagation and the recursion shown, the StaleObjectStateException would eventually clear but this isn't the case.
如何从此异常中恢复?
推荐答案
结果是我忽略了一些盖塔"图案.
Turns out there's a bit of a 'gatcha' which I've overlooked...
来自spring文档
在代理模式(默认)下,仅外部"方法调用 通过代理服务器传入的邮件将被拦截.这意味着 自调用",即目标对象中的一种调用某些方法的方法 目标对象的其他方法,不会导致实际交易 即使在调用的方法上标有@Transactional的情况下,在运行时也是如此!
In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!
因为我一直在内部进行递归,所以未应用事务划分.
Because I've been recursing internally, the transaction demarcation wasn't getting applied.
解决方案是像这样通过代理进行递归...
The solution is to recurse via the proxy, like this...
@Autowired
private ApplicationContext applicationContext;
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void doSomeWork(){
Entity = entity = dao.loadEntity();
// do some related work
...
try {
dao.saveEntity(entity);
}
catch(StaleObjectStateException sose){
dao.flush(entity);
applicationContext.getBean(this.getClass()).doSomeWork();
}
}
这篇关于从休眠乐观锁定异常中恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!