Skip to content

Commit

Permalink
[datasource] ensure tomcat datasource withconnection rolls back the c…
Browse files Browse the repository at this point in the history
…onnection on SQLExceptions
  • Loading branch information
rmannibucau committed Jun 20, 2023
1 parent e393f31 commit 7b1aa81
Showing 1 changed file with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ protected TomcatDataSource() {

/**
* Binds a connection to current thread in write mode, the result will be committed if there is no error.
*
* @param function the task to execute.
* @param <T> the returned type.
* @param <T> the returned type.
* @return the result of the function computation.
*/
public <T> T write(final Function<Connection, T> function) {
Expand All @@ -56,8 +57,9 @@ public <T> T write(final Function<Connection, T> function) {

/**
* Binds a connection to current thread in read-only mode, the result will be rolle-backed if needed.
*
* @param function the task to execute.
* @param <T> the returned type.
* @param <T> the returned type.
* @return the result of the function computation.
*/
public <T> T read(final Function<Connection, T> function) {
Expand Down Expand Up @@ -95,7 +97,9 @@ public Connection current() {
}

public <T> T withConnection(final SQLFunction<Connection, T> function) {
Connection conRef = null;
try (final var connection = super.getConnection()) {
conRef = connection;
connectionThreadLocal.set(wrap(connection));
final var original = disableAutoCommit(connection);
try {
Expand All @@ -109,6 +113,13 @@ public <T> T withConnection(final SQLFunction<Connection, T> function) {
restoreAutoCommit(connection, original);
}
} catch (final SQLException ex) {
try {
if (conRef != null && !conRef.isClosed()) {
conRef.rollback();
}
} catch (final SQLException e) {
ex.addSuppressed(e);
}
throw new IllegalStateException(ex);
} finally {
connectionThreadLocal.remove();
Expand Down

0 comments on commit 7b1aa81

Please sign in to comment.