Spring 事务因 RuntimeException 回滚
Spring transaction rolled back on RuntimeException
我有一个事务方法,我想调用另一个可能会抛出 RuntimeException 的方法。
问题是事务被标记为 rollbackOnly 当抛出异常时。
另一个方法调用本身在 try-catch 块中,但我认为当另一个方法 returns 抛出异常时事务被标记。
示例:
MyService.java
@Service
public class MyService {
@Autowired
private MyUtils utils;
@Autowired
private MyCrudRepository repository;
@Transactional
public void publicMethod() {
try {
utils.otherPublicMethod();
} catch (Exception ex) {
ex.printStackTrace();
}
// RollbackException: Transaction marked as rollbackOnly
// Even though I caught the exception from the method call itself
repository.save(new MyEntity());
}
}
MyUtils.java
@Component
public class MyUtils {
// Does not use transactions, repositories
// But I think it inherits the transaction and marks it as rollbackOnly
public void otherPublicMethod() {
// Maybe this is seen as an uncaught exception
throw new RuntimeException();
}
}
编辑:
我不认为这是 Does Specifying @Transactional rollbackFor Also Include RuntimeException 的重复,因为异常最终会被捕获。
问题可能类似,因为它也涉及事务和回滚。
注解@Transactional
有rollbackFor
和no-rollback-for
等参数,你可以用它们来说明哪些异常会导致或不会导致回滚。例如你可以写:
@Transactional(rollbackFor = {RuntimeException.class})
这将导致 RuntimeException
回滚。但是,我相信 RuntimeException
默认情况下会导致回滚。所以你可能必须在 no-rollback-for
子句中指定这个例外。
有关详细信息,请参阅 Transaction Management 并查找“16.5.5 设置”段落
我有一个事务方法,我想调用另一个可能会抛出 RuntimeException 的方法。
问题是事务被标记为 rollbackOnly 当抛出异常时。
另一个方法调用本身在 try-catch 块中,但我认为当另一个方法 returns 抛出异常时事务被标记。
示例:
MyService.java
@Service
public class MyService {
@Autowired
private MyUtils utils;
@Autowired
private MyCrudRepository repository;
@Transactional
public void publicMethod() {
try {
utils.otherPublicMethod();
} catch (Exception ex) {
ex.printStackTrace();
}
// RollbackException: Transaction marked as rollbackOnly
// Even though I caught the exception from the method call itself
repository.save(new MyEntity());
}
}
MyUtils.java
@Component
public class MyUtils {
// Does not use transactions, repositories
// But I think it inherits the transaction and marks it as rollbackOnly
public void otherPublicMethod() {
// Maybe this is seen as an uncaught exception
throw new RuntimeException();
}
}
编辑:
我不认为这是 Does Specifying @Transactional rollbackFor Also Include RuntimeException 的重复,因为异常最终会被捕获。
问题可能类似,因为它也涉及事务和回滚。
注解@Transactional
有rollbackFor
和no-rollback-for
等参数,你可以用它们来说明哪些异常会导致或不会导致回滚。例如你可以写:
@Transactional(rollbackFor = {RuntimeException.class})
这将导致 RuntimeException
回滚。但是,我相信 RuntimeException
默认情况下会导致回滚。所以你可能必须在 no-rollback-for
子句中指定这个例外。
有关详细信息,请参阅 Transaction Management 并查找“16.5.5 设置”段落