在 spring 中,如何在事务回滚发生一次迭代后继续来自 Controller for 循环的请求

In spring , How to continue the request from the Controller for loop after transactional rollback happened for one iteration

在服务中发生任何回滚后请求正在关闭layer.It 未从控制器继续。

例如:

public Class UserController {
 @Autowired
 UserService userService;
 createUserList(List < User > list) {
  try {
  RespObj obj=new RespObj();
   List < Obj > errorList = new ArrayList();
   for (User user: list) {
    Object obj = userService.createUser(user);
    errorList.add(obj);
   }
   //return success response along with any errorlist
   obj.setStatus(200);
   obj.setObj(errorList);
   return obj;
  } catch (Exception e) {
   //returning error response 
   obj.setStatus(400);
   obj.setObj(e.getMessage());
   return obj; 
  }
 }
}

//UserServiceImpl

public class UserServiceImpl implements UserService {
 @Transactional
 Object createUser(user) {
  try {
   dao.saveUser(user);
  } catch (Exception e) {
   //create error pojo 
  }
  // return error pojo if any
 }
}

在上面的代码中,如果任何一个用户创建失败,回滚只会针对该用户发生,之后不会处理剩余的用户对象。

要求是:留下一个失败的,需要处理剩余的未处理的用户对象。

如果您的服务是事务性的并且您在循环中调用它,则必须在循环内捕获异常。 这是处理多个项目的请求的普遍问题。应该拒绝所有项目还是收集失败的项目....

您的示例代码似乎没有您描述的问题,因为:

  1. 您已捕获异常并在 createUser 方法中处理它,异常不会传播到控制器。控制器会继续处理下一个。
  2. 服务方法中注释了事务性,这是正确的。每当服务方法 returned 到控制器并且事务结束时,将在处理下一个用户时创建一个新的。

您描述的问题似乎是您没有在服务内部处理异常。

另一种可能是您在 catch 子句或 return 语句中有另一个异常。

像这样更新您的代码以处理所有用户,将错误添加到 errorList。

RespObj obj=new RespObj();
List < Obj > errorList = new ArrayList();
for (User user: list) {
 User user = new Object;
 try {
     user = userService.createUser(user);
   } catch (Exception e) {
      obj.setMessage(e.getMessage());
      obj.setStatus(400);
      errorList.add(obj);
     }
   }
   obj.setStatus(200);
   obj.setErrorList(errorList);
   return obj;
 }