Search code examples
mysqlspringjparollbacktransactional

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


Request is closing after any rollback happened in the service layer.It is not continuing from the controller.

ex:

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
 }
}

In above code if any one user creation is fails, roll back is happening for that user alone and after that remaining user objects are not processing.

Requirement is :leave the one failed and Need to process the remaining user objects which were not processed .


Solution

  • Update your code like so to process all users, add errors to 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;
     }