1

I have the following two method to store the single user and multiple users in mongodb using Spring data JPA's MongoRepository. If any exception happened in the method it is not rollbacking. I can able to find the data in database.

@Override
@Transactional(propagation = Propagation.REQUIRED)
public UserRequest save(UserRequest userRequest) throws UserException {
    logger.info("Saving the user information {} ", userRequest);
    User user = new User(sequenceService.getNextSequenceFor(SequenceNames.USER));
    if("admin".equals(userRequest.getFirstName())) {
        throw new UserException("Resvered name canot be used : " + userRequest.getFirstName());
    }
    BeanUtils.copyProperties(userRequest, user,"id");
    user = userRepository.save(user);
    userRequest.setId(user.getId());
    return userRequest;
}


@Override
@Transactional
public List<UserRequest> save(List<UserRequest> users) throws UserException {
    for (UserRequest userRequest : users) {
        save(userRequest);
    }
    return users;
}


@Repository
public interface UserRepository extends MongoRepository<User, String> {

}

User Request :

[
    {
        "firstName": "John",
        "lastName": "A",
        "mobileNo": "9898989892",
        "emailId": "john.a@gmail.com"
    },
    {
        "firstName": "admin",
        "lastName": "A",
        "mobileNo": "9898989892",
        "emailId": "admin.a@gmail.com"
    }
]

This code saves the John's data in database. It is rollback only for the user admin. It doesn't rollback for all the user data. Partial roolback is not happening.

noiaverbale
  • 1,550
  • 13
  • 27
Sathyendran a
  • 1,709
  • 4
  • 21
  • 27
  • Where is the code located which calls the save methods? – C. Weber Feb 06 '19 at 16:37
  • 1
    The exception should be RuntimeException [Spring Transactions](https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/transaction.html) _Any RuntimeException triggers rollback, and any checked Exception does not._ For the rollback to happen and you can use `@Transactional(rollbackFor = UserException.class)` – azl Feb 06 '19 at 17:56

1 Answers1

0

Before Release 4, MongoDB has been supporting atomicity only on the level of a single document. Spring Data Mongo does not provide any extra functionality to overcome this drawback. However, as of MongoDB 4 and Spring Data Mongo 2.1 this can be achived by configuring a MongoTransactionManager, see Spring Data Mongo documentation. However, I am not sure whether any of the Propagation options (coming from the JPA spec) apply to the MongoDB transaction functionality.

seb.wired
  • 456
  • 1
  • 3
  • 12