Here is the behavior I wish to achieve:
@Transactional(rollbackFor = NullPointerException.class)
@PostMapping(consumes = {"application/json"})
public Employee createEmployee(@Valid @RequestBody Employee employee) {
Optional<Department> departmentOptional = departmentRepository.findById(employee.getDeptId());
EmployeeAggregate employeeAggregate = employeeAggregateRepository.findAll().get(0);
employeeAggregate.setTotalEmployeeCount(employeeAggregate.getTotalEmployeeCount()+1);
employeeAggregateRepository.save(employeeAggregate); <--This line should be rolled back when exception is thrown.
if(departmentOptional.isPresent()) {
Department department = departmentOptional.get();
return employeeRepository.save(employee);
}
else{
throw new NullPointerException();
}
}
There are two documents, Employees, and EmployeeAggregate. I want to be able to rollback the employee count stored in EmployeeAggregate if I am unable to create an employee in Employees document.
Here is my mongo config file:
@Configuration
public class MongoConfig {
@Bean
@Autowired
@ConditionalOnExpression("'${mongo.transactions}'=='enabled'")
MongoTransactionManager mongoTransactionManager(MongoDbFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
public @Bean MongoClient mongoClient() {
return new MongoClient("localhost");
}
public @Bean
MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(), "EmployeeDatabase");
}
}
Currently, no rollback takes place if Employee creation fails. The count gets updated by one irrespective of successful employee creation or not. An explanation of multidocument transactions in spring boot would be appreciated, since the documentation is a bit confusing.