在查询超时后,Spring的JdbcTemplate会关闭连接吗?

nimxete2  于 2022-10-04  发布在  Spring
关注(0)|答案(4)|浏览(361)

我在使用INSERT语句的方法中设置了查询超时(getJdbcTemplate().setQueryTimeout(5))。查询超时后会发生什么,JDBC模板会关闭我的连接吗?

bq8i3lrv

bq8i3lrv1#

简而言之,是的,它确实关闭了这种联系。答案很长,视情况而定。

当您没有Spring托管事务时,是的,JdbcTemplate将调用Connection上的close()方法。然而,如果由于Springs事务管理已经存在可用的连接,则关闭连接将由Springs事务支持处理,而后者又将在Connection上调用close()

唯一的区别是何时关闭连接,但将调用close()

如果实际关闭连接取决于使用的DataSource,通常在使用连接池时,连接将返回到池中,而不是实际关闭连接。

yc0p9oo0

yc0p9oo02#

是的。

如果连接是从连接池获得的,它实际上不会关闭连接,而是将其发送回池。

pn9klfpd

pn9klfpd3#

无需手动关闭连接。Spring容器本身负责操作。请参阅此Spring文档:

Https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#jdbc

mbyulnm0

mbyulnm04#

通过回顾JdbcTemplate的源代码,有一种方法叫做execute,它是其他一些查询方法的基础,如queryForObjectqueryForList等:

@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());
            }
        }
    }

显然,当调用Execute Get时,数据库连接将在Finally块中被释放,因此,没有必要在查询超时后关闭连接。

相关问题