[英]Spring transaction not rolled back after an exception is thrown
我有一个带有方法的服务,它没有用@Transactional
注释:
@Service
@RequiredArgsConstructor
public class MainService {
private final ServiceA serviceA;
public void processData() {
List<EntityA> list = serviceA.getList();
list.forEach(item -> {
try {
serviceA.doSomeDbOperations(item);
} catch(Exception e) {
// some processing here
} finally {
// some processing and DB interactions here
}
})
}
}
目标是在抛出异常时回滚 try 块 ( serviceA.doSomeDbOperations(item)
) 中发生的更改。 所以我在 ServiceA 中用@Transactional
注释了这个方法:
@Service
public class ServiceA {
// dependencies
@Transactional
public void doSomeDbOperations(EntityA item) {
// some logic here
repositoryA.save(item)
serviceB.deleteSomething(input)
}
}
serviceB.deleteSomething(input)
可能会抛出异常:
@Service
public class ServiceB {
// dependencies
public void deleteSomething(EntityA item) {
// some logic here
if(condition) {
Throw new RuntimeException();
}
}
}
问题是当抛出异常时,try 块中的更改不会回滚,数据不一致。 知道问题出在哪里吗?
我猜在 ServiceB 中您正在使用已检查的异常。 在 Spring 中,默认情况下,事务仅在未经检查的异常上回滚,因此请尝试在 ServiceB.deleteSomething() 方法中抛出例如 RuntimeException 。
如果您需要检查异常,您可以在 ServiceA.doSomeDbOperations() 方法中执行以下操作:
@Transactional(rollbackFor = Throwable.class)
一些参考资料:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.