即使提供了@ EnableTransactionManagement,@ Transactional批注也不会回滚RuntimeException
问题描述:
我具有以下应用程序设置:
I have the following application setup:
@SpringBootApplication
@EnableTransactionManagement
public class MyApp extends SpringBootServletInitializer {
...
}
具有一个具有以下内容的类:
with a class which has the following:
public class DoStaff {
public void doStaffOnAll(List<MyObject> myObjects) {
for (int i=0; i<myObjects.size(); i++) {
try {
doStaffOnSingle(myObjects.get(i), i);
} catch (Exception e) {
e.printStrackTrace();
}
}
}
@Transactional
public void doStaffOnSingle(MyObject myObject, int i) {
repository.save(myObject);
if (i%2==0) {
throw new RuntimeException();
}
}
}
因此,如果我使用 MyObject
的列表调用 DoStaff.doStaffOnAll
,则代码将保存列表中的所有元素,但还会为第二个元素引发运行时异常.
So if I call DoStaff.doStaffOnAll
with a list of MyObject
s, the code saves all element from the list but also throws a runtime exception for every second element.
由于 doStaffOnSingle
具有 @Transactional
批注,所以我希望每隔两个元素都会回滚一次.但是,如果我运行此代码,则每个元素都会成功保存在数据库中.这是为什么?我在做什么错了?
Since the doStaffOnSingle
has @Transactional
annotation, I would expect that every second element will be rolled back.
But if I run this code, every element is saved in the DB successfully. Why is that? What am I doing wrong?