问题描述
美好的一天.代码如下:
Good day. The following code:
class A{
private B b;
@Transactional
public SomeResult doSomething(){
SomeResult res = null;
try {
// do something
} catch (Exception e) {
res = b.saveResult();
}
return res ;
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
class B{
public SomeResult saveResult(){
// save in db
}
}
据我所知,如果方法 doSomething
中出现异常,则事务不会回滚.以及如何使它滚动?并返回 SomeResult
As I understand, if there is an exception in the method doSomething
the transaction isn't rolled back. And how to make that it rolled? and returned SomeResult
推荐答案
您不应该以编程方式调用 Rollback.最好的方法,正如 docs,是使用声明式方法.为此,您需要注释哪些异常会触发回滚.
You shouldn't call Rollback programmatically. The best way, as recommended by the docs, is to use declarative approach. To do so, you need to annotate which exceptions will trigger a Rollback.
在你的情况下,像这样
@Transactional(rollbackFor={MyException.class, AnotherException.class})
public SomeResult doSomething(){
...
}
看看@Transaction API 和关于 回滚事务.
如果不顾文档的建议,您想要进行编程回滚,那么您需要按照已经建议的那样从 TransactionAspectSupport
调用它.这是来自文档:
If, despite the docs recommendation, you want to make a programmatic rollback, then you need to call it from TransactionAspectSupport
as already suggested. This is from the docs:
public void resolvePosition() {
try {
// some business logic...
} catch (NoProductInStockException ex) {
// trigger rollback programmatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
不过可能存在架构错误.如果您的方法失败并且您需要抛出异常,则不应期望它返回任何内容.也许你给这个方法太多的责任,应该创建一个单独的只对数据建模的方法,如果出现问题则抛出异常,回滚事务.无论如何,请阅读文档.
There may be a architecture mistake though. If your method fails and you need to throw an exception, you shouldn't expect it to return anything. Maybe you're giving too much responsibilities to this method and should create a separated one that only model data, and throws an exception if something goes wrong, rolling back the transaction. Anyway, read the docs.
这篇关于回滚一个@Transactional 注释的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!