That depends where that transaction comes from. In Java/JDBC, a transaction is tied to a connection. You start one by setting setAutoCommit()
to false (otherwise, every statement becomes its own little transaction).
There is nothing preventing you from reusing the connection after a transaction failed (i.e. you called rollback).
Things get more tricky when you use Spring. Spring wraps your methods in a transaction handler and this handler tries to guess what it should do with the current transaction from the exceptions that get thrown in the method. The next question is: Which wrapper created the current transaction? I just had a case where I would call a method foo()
which would in turn call bar()
, both @Transactional
.
I wanted to catch errors from bar()
in foo()
and save them into the DB. That didn't work because the transaction was created for foo()
(so I was still in a transaction which Spring thought broken by the exception in bar()
) and it wouldn't let me save the error.
The solution was to create baz()
, make it @Transactional(propagation=Propagation.REQUIRES_NEW)
and call it from foo()
. baz()
would get a new, fresh transaction and would be able to write to the DB even though it was called from foo()
which already had a (broken) transaction.