我有用于 sql 语句的 jdbs 模板,并使用 hikari 连接池,经过几次调用后我出现异常,我使用了 try-with-resources,我的错误在哪里?(Servlet Container -Tomcat)
public class SimpleJdbcTemplate {
private Connection connection;
private DataSource dataSource;
private ResultSet resultSet;
PreparedStatement preparedStatement;
public SimpleJdbcTemplate(Connection connection) {
this.connection = connection;
}
//private DataSourse datasource - из hikariconnectionpool
public SimpleJdbcTemplate(DataSource dataSource) {
this.dataSource = dataSource;
}
public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args) {
try (PreparedStatement preparedStatement = dataSource.getConnection().prepareStatement(sql)){
resultSet = null;
List<T> result = new ArrayList<>();
int position = 1;
for (Object arg : args) {
preparedStatement.setObject(position, arg);
position++;
}
if (sql.contains("UPDATE") || sql.contains("update") ||sql.toLowerCase().contains("delete")||sql.toLowerCase().contains("insert")) {
preparedStatement.executeUpdate();
} else{
resultSet = preparedStatement.executeQuery();
if (resultSet == null) {
throw new SQLException("No resultsSet");
}
while (resultSet.next()) {
result.add(rowMapper.mapRow(resultSet));
}
}
log.info(result.toString());
return result;
} catch (SQLException e) {
throw new IllegalStateException(e);
日志:
2020 年 10 月 24 日 13:46:16.633 严重 [http-nio-8080-exec-3] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() 用于 servlet [servlets.view.MessendjerViewServlet]路径 [/LabWork_war] 抛出异常 java.lang.IllegalStateException: java.sql.SQLTransientConnectionException: HikariPool-1 - 连接不可用,请求在 30014 毫秒后超时。在 repository.utill.SimpleJdbcTemplate.query(SimpleJdbcTemplate.java:52) 在 repository.jdbc.UserRepositoryImpl.findUserByUUID(UserRepositoryImpl.java:84) 在 service.UserService.findUser(UserService.java:71) 在 servlets.filter.AuthFilter。 doFilter(AuthFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache . AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) at org.apache.tomcat.util.net.SocketProcessorBase.run( SocketProcessorBase.java:49) 在 java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) 在 java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)在 org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 在 java.base/java.lang.Thread.run(Thread.java:832) 引起:java.sql.SQLTransientConnectionException :HikariPool-1 - 连接不可用,请求在 30014 毫秒后超时。在 com.zaxxer.hikari.pool.HikariPool.getConnection(HikariPool.java:197) 的 com.zaxxer.hikari.pool.HikariPool.createTimeoutException(HikariPool.java:695)。