1

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.

  • 1
    Both cases are the same. Internal method calls don't pass through the proxy, next to that an `@Transactional` will just participate in an already existing transaction (unless there is a different propagation level like `REQUIRES_NEW` but that doesn't make a difference here as they are internal method calls). – M. Deinum Aug 14 '18 at 07:48
  • It means that in both cases the operations are performed within a single transaction? Is the rollback operation performed because of this reason? Thanks a lot @M.Deinum – Suraj Gautam Aug 14 '18 at 08:19
  • Yes. There is just a single transaction. – M. Deinum Aug 14 '18 at 08:23

0 Answers0