I have a code like this one:
jdbi.inTransaction(h -> {
Dao1 dao1 = h.attach(Dao1.class);
if(!dao1.somequery()) {
throw new CustomException("foobar");
}
// ... other statements
}
Can I be sure that if CustomException
is thrown jdbi
will rollback the transaction or this happen only with SQLException
or Jdbi related Exceptions ?
Let's consider Jdbi 3.27.0.
Please, see the Javadoc for the org.jdbi.v3.core.Jdbi#inTransaction(org.jdbi.v3.core.HandleCallback<R,X>)
method:
inTransaction
public <R, X extends Exception> R inTransaction (HandleCallback<R,X> callback) throws X
A convenience function which manages the lifecycle of a handle and yields it to a callback for use by clients. The handle will be in a transaction when the callback is invoked, and that transaction will be committed if the callback finishes normally, or rolled back if the callback raises an exception.
Type Parameters:
R
- type returned by the callback
X
- exception type thrown by the callback, if any.Parameters:
callback
- A callback which will receive an open Handle, in a transactionReturns:
the value returned by callback
Throws:
X
- any exception thrown by the callback
Please, note the text marked in bold, which should answer your question:
The handle will be in a transaction when the callback is invoked, and that transaction will be committed if the callback finishes normally, or rolled back if the callback raises an exception.
Throws:
X
- any exception thrown by the callback
As we can see, there is no statement claiming that the exception handling behavior depends on the exception type.
Please, consider the information provided in this section as a draft: it may be rough (imprecise).
There are tests that cover the transaction-related functionality.
The tests are represented by the TestTransactions
class: jdbi/TestTransactions.java at v3.27.0 · jdbi/jdbi.
Please, take a look at the entire test class.
Then, please, note the following exception-related test methods:
testExceptionAbortsTransaction()
.testExceptionAbortsUseTransaction()
.As we can examine from the implementations of these test methods:
java.io.IOException
exception type.