使用try catch块时的Spring @Transactional注释
如果我们在带有@Transactional
注释的方法中捕获到异常,如果发生任何异常,它将回滚吗?
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor=Throwable.class)public void yearEndProcess() {
try {
// try block
} catch (Throwable throwable) {
// catch block
}
}
回答:
例如
class A{ @Transactional
public Result doStuff(){
Result res = null;
try {
// do stuff
} catch (Exception e) {
}
return res ;
}
}
如果有一个例外,在方法doStuff
的
To rollback the exception programmatically
,我们可以执行以下操作。
@Transactional(rollbackFor={MyException1.class, MyException2.class, ....})public Result doStuff(){
...
}
您需要从中调用它TransactionAspectSupport
。
public Result doStuff(){ try {
// business logic...
} catch (Exception ex) {
// trigger rollback programmatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
You are spanly encouraged to use the `declarative approach` to `rollback` if at all possible.
`Programmatic rollback` is available should only be used if you absolutely need it.
以上是 使用try catch块时的Spring @Transactional注释 的全部内容, 来源链接: utcz.com/qa/425080.html