I was testing some code and found an interesting scenario.
Scenario:
public class ServiceA {
public List<Object> saveAndGetAllV1() {
serviceB.saveAll();
return getAll();
}
public List<Object> saveAndGetAllV2() {
serviceB.saveAll();
return serviceB.getAll();
}
@Transactional(propagation = Propagation.MANDATORY)
public List<Object> getAll() {
repository.findAll();
}
}
public class ServiceB {
public void saveAll() {
serviceC.saveAll();
}
public List<Object> getAll() {
return repository.findAll();
}
}
public class ServiceC {
public void saveAll() {
repository.saveAll(object);
}
@Transactional(propagation = Propagation.MANDATORY)
public List<Object> getAll() {
return repository.findAll();
}
}
The method saveAndGetAllV1()
does not give any error even when the transaction is mandatory in serviceA.getAll()
method. While on the other hand saveAndGetAllV2()
gives error as serviceC.getAll()
requires mandatory transaction.
So my question is why in serviceA.getAll()
method the transaction is automatically created but in serviceC.getAll()
method the transaction is not automatically created?