![](/img/trans.png)
[英]Will an unchecked exception thrown and caught inside a method annotated with spring's @Transactional still cause the transaction to rollback?
[英]Exception are not getting caught inside method annotate with @Transactional
在 spring 引导注释中从 Controller 调用 update() 并使用 @Transactional 进行注释,并且此 update() 调用 update2()。 因此,当我尝试使用 update2() 将重复值保存到我的数据库中时,它不会向 update() 抛出异常,而是转到 Controller 方法。 我想在 update() 中处理异常。
@Transactional(rollbackFor = Exception.class)
public String update()
{
try
{
return update2();
}
catch (Exception e) {
return "Exception in update()";
}
}
public String update2() throws Exception
{
List<Employee> l = repo.findAll();
for(int i=0 ; i<2 ; i++)
{
if(i==0)
l.get(i).setUsername("duplicate_value");
else
l.get(i).setUsername("unique_value");
repo.save(l.get(i));
}
return "success";
}
正如Hadi Moloodi在评论中提到的那样,您的@Transactional
注释是使您的Exception
无法捕获的原因。
您可以尝试将@Transactional
注释移动到您的update2
方法,如下所示:
public String update() {
try {
return update2();
} catch (Exception e) {
return "Exception in update()";
}
}
@Transactional(rollbackFor = Exception.class)
public String update2() throws Exception {
List<Employee> l = repo.findAll();
for(int i=0 ; i<2 ; i++) {
if(i==0) {
l.get(i).setUsername("duplicate_value");
} else {
l.get(i).setUsername("unique_value");
}
repo.save(l.get(i));
}
return "success";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.