I have set query timeout (getJdbcTemplate().setQueryTimeout(5)) in method with insert statement. What will happen after query timeout, does jdbc template close my connection?
I have set query timeout (getJdbcTemplate().setQueryTimeout(5)) in method with insert statement. What will happen after query timeout, does jdbc template close my connection?
In short yes it does close the connection. The long answer it depends.
When you don't have a Spring managed transaction then yes the JdbcTemplate will call the close() method on the Connection. However if there was already a connection available due to Springs transaction management closing the connection will be handled by Springs transaction support, which in turn also will call close() on the Connection.
The only difference is when the connection is closed but close() will be called.
If the connection will be actually closed depends on which DataSource is used, in general when using a connection pool the connection will be returned to the pool instead of actually closing the connection.
Yes it does.
And if the connection was obtained from connection pool, it won't actually close the connection, rather will send it back to the pool.
We can also close connection while using jdbcTemplate, in some cases it is compulsory to close connection after executing a query otherwise you'll get connection issue. For more details visit Close connection in jdbc template
jdbcTemplate.getDataSource().getConnection().close();
By reviewing the source code of JdbcTemplate, there is a method called execute, which is the infrastructure of some other query method, such as queryForObject, queryForList and so on :
@Nullable
private <T> T execute(StatementCallback<T> action, boolean closeResources) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
T result = action.doInStatement(stmt);
handleWarnings(stmt);
return result;
}
catch (SQLException ex) {
// Release Connection early, to avoid potential connection pool deadlock
// in the case when the exception translator hasn't been initialized yet.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
if (closeResources) {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
}
Apparently, when execute get called, the database connection would be release in the finally block , as a result, it`s unnecessary to close the connection after query timeout.