Jdbi3 是否保证每种异常类型的事务回滚?

Does Jdbi3 guarantee rollback on transaction for every type of Exception?

我有这样一个代码:

jdbi.inTransaction(h -> {
            
            Dao1 dao1 = h.attach(Dao1.class);
            
            if(!dao1.somequery()) {
                
                throw new CustomException("foobar");
            }

            // ... other statements
}

我能否确定如果 CustomException 被抛出 jdbi 将回滚事务或者这仅发生在 SQLException 或 Jdbi 相关异常时?

简介

让我们考虑Jdbi 3.27.0.

文档

请参阅 the Javadoc org.jdbi.v3.core.Jdbi#inTransaction(org.jdbi.v3.core.HandleCallback<R,X>) 方法:

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 transaction

Returns:

the value returned by callback

Throws:

X - any exception thrown by the callback

请注意粗体标记的文字,它应该可以回答您的问题:

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

正如我们所见,没有声明声称异常处理行为取决于异常类型。

源代码

请将本节中提供的信息视为草稿:它可能很粗糙(不精确)。

有涵盖 transaction-related 功能的测试。
测试由 TestTransactions class 表示:jdbi/TestTransactions.java at v3.27.0 · jdbi/jdbi.

请看一下整个测试 class。

那么,请注意以下exception-related测试方法:

  1. testExceptionAbortsTransaction().
  2. testExceptionAbortsUseTransaction().

我们可以从这些测试方法的实现中检查:

  1. 实现使用 java.io.IOException 异常类型。
  2. 实现没有提到异常处理行为取决于异常类型。