I have this situation
@Component
@Slf4j
public class MainClass {
@Autowired
private SomeService service;
@Autowired
private OtherService otherService;
@Transactional
private Object save() {
List<Object> objects = processSomething();
return otherService.save(objects);
}
private List<Object> processSomething() {
return service.doSomething();
}
}
@Service
@Transactional
@Slf4j
public class SomeService {
@Autowired
private SomeService service;
public Object doSomething() {
List<Object> objects = List.of(new Object());
doSomethingAfterCommit();
return objects;
}
private void doSomethingAfterCommit() {
if (!TransactionSynchronizationManager.isActualTransactionActive()) return;
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
@Override
public void afterCommit() { // triggered before otherService.save() call
// some db operations to find records saved in otherService.save()
}
});
}
}
@Service
@Transactional
@Slf4j
public class OtherService {
public Object save(List<Object> objects) {
// db operations to save all entities and returns one
}
}
I'm confused as to why the afterCommit in doSomethingAfterCommit is being called before the save method of OtherService can even start. With how I set the Transactional annotations I thought all db operations would all be part of the same transaction, so the afterCommit would be called at the end of MainClass.save(). Why isn't it happening?