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