I was reading about declarative transaction management in Spring Framework and I tried to make my hands dirty. Below are the two cases:
Case-1: The method testTransaction is called from controller and there is no @Transaction annotation present at type level.
@Override
@Transactional
public void testTransaction() {
saveFoo2();
saveFoo();
}
private void saveFoo2() {
fooRepository.save(new Foo(null, "asd"));
}
private void saveFoo() {
fooRepository.save(new Foo(null, "zxzxczxxc"));
throw new RuntimeException("Rollback please");
}
Case-2: The method testTransaction is called from controller and there is no any @Transaction annotation present at type level.
@Override
@Transactional
public void testTransaction() {
saveFoo2();
saveFoo();
}
@Transactional
public void saveFoo2() {
fooRepository.save(new Foo(null,"asdasd"));
}
@Transactional
public void saveFoo() {
fooRepository.save(new Foo(null,"zxczaxc"));
throw new RuntimeException("Rollback please");
}
As per my understanding,
In Case-1: Whenever the testTransaction method is invoked, the transaction is created and the same transaction is propagated to saveFoo2() and saveFoo() method and any runtimeexception inside the same transaction will rollback.
In case-2: The spring transaction works with proxies and whenever the internal call from the same bean occurs, then the transaction must not rollback. Reference But in this case, saveFoo2() and saveFoo() is called from the same instance but also the transaction is rolling back. I am unclear about it.
Is my understanding correct? Could you please point me that what I am missing? I have done a lot of research but couldn't figure it out. It would be a great help.