簡體   English   中英

Spring 的 JdbcTemplate 是否在查詢超時后關閉連接?

[英]Does Spring's JdbcTemplate close the connection after query timeout?

我在帶有插入語句的方法中設置了查詢超時 (getJdbcTemplate().setQueryTimeout(5))。 查詢超時后會發生什么,jdbc 模板會關閉我的連接嗎?

簡而言之,它確實關閉了連接。 長答案取決於。

當您沒有 Spring 托管事務時,是的JdbcTemplate將調用Connection上的close()方法。 但是,如果由於 Springs 事務管理關閉連接已經有可用的連接,則 Springs 事務支持將處理該連接,后者也會在Connection上調用close()

唯一的區別是連接關閉但close()將被調用。

連接是否實際關閉取決於使用的是哪個DataSource ,通常在使用連接池時,連接將返回到池中,而不是實際關閉連接。

是的,它確實。

如果連接是從連接池中獲得的,它實際上不會關閉連接,而是將其發送回連接池。

無需手動關閉連接。 Spring 容器本身采取的操作。 請參考這個春天的網址,

http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html

我們也可以在使用jdbcTemplate關閉連接,在某些情況下,執行查詢后必須關閉連接,否則會出現連接問題。 有關更多詳細信息,請訪問jdbc 模板中的關閉連接

jdbcTemplate.getDataSource().getConnection().close();

通過查看 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塊中釋放,因此查詢超時后無需關閉連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM