在 Spring Boot 中使用 @Transactional 注释从 Controller 调用 update(),并且此 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";
}
关于java - 使用 @Transactional 注释的方法内部不会捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58498102/