0

I'm using springboot 2.3.0 with mongodb. @Transactional annotation is not working for me. It is not able to rollback the transaction in case of any exception. ps:Using mongoTemplate it is working.

Any help will be highly appreciated.

My controller class:

@PostMapping(value = "/employee/{employeeId}")
public String createEmployee(@PathVariable(value = "employeeId") String employeeId, @RequestBody EmployeePayload payload) {
    
    employeeService.createEmployee(employeeId, payload);
    return "employee successfully added";
}

My serviceImpl class

@Override
@Transactional(rollbackFor = {ArithmeticException.class})
public void createEmployee(String employeeId, EmployeePayload payload) {
    Employee employee = new Employee("1", "Robert", "24");
    Document mongoDocument = new Document();
    mongoTemplate.getConverter().write(employee, mongoDocument);
    MongoDatabaseFactory mongoDatabaseFactory = new 
    SimpleMongoClientDatabaseFactory(properties.getUri()
            + properties.getDataBase() 
            + properties.getDbFilter());

    MongoDatabaseUtils.getDatabase(properties.getDataBase(), 
    mongoDatabaseFactory).getCollection("employee").insertOne(mongoDocument);
    System.out.println(7 / 0); //To throw an exception
}

My MongoConfig class

@Configuration public class MongoDBConfig {

    @Bean
    MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
        return new MongoTransactionManager(dbFactory);
    } 
}
NEHA
  • 11
  • 2
  • Does this answer your question? [Spring @Transactional rollbackFor not working](https://stackoverflow.com/questions/22957569/spring-transactional-rollbackfor-not-working) – Aris Mar 31 '21 at 14:06
  • What kind of MongoDB deployment is it? – prasad_ Apr 01 '21 at 06:59

1 Answers1

0

You are missing @EnableTransactionManagement annotation.

Akif Hadziabdic
  • 2,692
  • 1
  • 14
  • 25