Skip to content

Commit

Permalink
refactor: 4단계 피드백 - transaction 적용을 하지 않는 데이터베이스 작업은 실행 후 Connection …
Browse files Browse the repository at this point in the history
…연결을 끊도록 하기
  • Loading branch information
BackFoxx committed Oct 12, 2023
1 parent 4a0ba70 commit 5e0c2ed
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import javax.sql.DataSource;
import org.springframework.dao.SQLExceptionTranslator;
import org.springframework.dao.SQLNonTransientConnectionException;
import org.springframework.jdbc.datasource.DataSourceUtils;

public class JdbcTemplate {
Expand All @@ -35,6 +36,8 @@ public int update(String sql, Object... parameters) {
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw SQLExceptionTranslator.translate(e);
} finally {
releaseIfNotTransacting(connection);
}
}

Expand All @@ -58,16 +61,8 @@ public <T> Optional<T> queryForObject(String sql, RowMapper<T> rowMapper, Object
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw SQLExceptionTranslator.translate(e);
}
}

private static void verifyResultRowSize(final ResultSet rs, final int rowSize) throws SQLException {
rs.last();
if (rowSize < rs.getRow()) {
throw new SQLException(String.format("결과가 1개인 줄 알았는데, %d개 나왔서!", rs.getRow()));
/**
* 예외 원문 : Incorrect result size: expected 1, actual n
*/
} finally {
releaseIfNotTransacting(connection);
}
}

Expand All @@ -89,6 +84,18 @@ public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... parameter
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw SQLExceptionTranslator.translate(e);
} finally {
releaseIfNotTransacting(connection);
}
}

private static void verifyResultRowSize(final ResultSet rs, final int rowSize) throws SQLException {
rs.last();
if (rowSize < rs.getRow()) {
throw new SQLException(String.format("결과가 1개인 줄 알았는데, %d개 나왔서!", rs.getRow()));
/**
* 예외 원문 : Incorrect result size: expected 1, actual n
*/
}
}

Expand All @@ -98,4 +105,14 @@ private static void setQueryParameters(final PreparedStatement pstmt, final Obje
pstmt.setObject(i, parameters[i - 1]);
}
}

private void releaseIfNotTransacting(final Connection connection) {
try {
if (connection.getAutoCommit()) {
DataSourceUtils.releaseConnection(connection, dataSource);
}
} catch (SQLException e) {
throw new SQLNonTransientConnectionException(e);
}
}
}

0 comments on commit 5e0c2ed

Please sign in to comment.