Skip to content

Commit

Permalink
fix: 커넥션이 중간에 close되는 문제 해결
Browse files Browse the repository at this point in the history
  • Loading branch information
JJ503 committed Oct 10, 2023
1 parent 2bfb86c commit 931503f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,8 @@ public <T> T execute(
final String sql,
final Object... args
) {
try (final Connection connection = DataSourceUtils.getConnection(dataSource)) {
return execute(connection, executeStrategy, sql, args);
} catch (SQLException e) {
log.error("exception : {}", e);
throw new RuntimeException(e);
}
final Connection connection = DataSourceUtils.getConnection(dataSource);
return execute(connection, executeStrategy, sql, args);
}

public <T> T execute(
Expand All @@ -47,6 +43,8 @@ public <T> T execute(
} catch (SQLException e) {
log.error("exception : {}", e);
throw new RuntimeException(e);
} finally {
DataSourceUtils.releaseConnection(connection, dataSource);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ public static Connection getConnection(DataSource dataSource) throws CannotGetJd

public static void releaseConnection(Connection connection, DataSource dataSource) {
try {
if (!connection.getAutoCommit()) {
return;
}

TransactionSynchronizationManager.unbindResource(dataSource);
connection.close();
} catch (SQLException ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public <T> T execute(final TransactionExecuteStrategy<T> executeStrategy) {
final Connection connection = DataSourceUtils.getConnection(dataSource);

try {
connection.setAutoCommit(false);
setAutoCommit(connection, false);

final T result = executeStrategy.strategy();

Expand All @@ -35,6 +35,7 @@ public <T> T execute(final TransactionExecuteStrategy<T> executeStrategy) {
rollback(connection);
throw new DataAccessException(e);
} finally {
setAutoCommit(connection, true);
DataSourceUtils.releaseConnection(connection, dataSource);
}
}
Expand All @@ -47,4 +48,12 @@ public void rollback(final Connection connection) {
throw new DataAccessException(e);
}
}

private void setAutoCommit(final Connection connection, final boolean status) {
try {
connection.setAutoCommit(status);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

0 comments on commit 931503f

Please sign in to comment.