2

这是我最近遇到的一些事情。

我对 Spring 的 JdbcTemplate 的理解是可以调用:

JdbcTemplate template = new JdbcTemplate(dataSource);
Connection conn = template.getDataSource().getConnection();

它使用传入的数据源返回来自 JdbcTemplate 的连接。如果我这样做:

template.getDataSource().getConnection().close();  

这只是获得另一个连接并关闭它,创建一个泄漏的资源,还是它让你得到它正在使用的连接?

编辑:

我在一个类中编写了 2 种方法,一种是编写 JDBC 语句的老式低级方法(使用连接、语句和结果集):

public void execute(String tableName) {
    try {
        Class.forName("com.ibm.as400.access.AS400JDBCDriver");
        Connection con = DriverManager.getConnection("jdbc:as400://viper", "******", "******"); 
        Statement select = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

        ResultSet rs = select.executeQuery ("SELECT * FROM ******." + tableName );
        logger.info("start clearing: " + tableName);

        while (rs.next ()) {
            rs.deleteRow();
        }
        logger.info("Step1 done clearing: " + tableName);

        ConnectionRecycler.recycleConnection(select, true, con);

        execute2(tableName);
    } catch (Exception eX) {
        logger.error(eX);
    }
}

另一种方法:

public void execute2(String tableName) {

    String nameOS = System.getProperty("os.name");
    String sql = (nameOS.equals("OS/400")) ? "DELETE from " + tableName : 
        "DELETE from " + tableName + " with none";

    JdbcTemplate templateSNPJ;

    templateSNPJ = new JdbcTemplate(this.snpjDataSource);
    templateSNPJ.update(sql);

    logger.info("Finished clearing: " + tableName);
    getServiceManager().unregisterService(this);
}

我以这种方式正确清理了资源。第二种方法是使用:

JdbcTemplate.update(sqlCommand);

但似乎 JdbcTemplate 使连接保持活动的时间比配置池的时间长。

我在 SO: Database connection management in Spring上阅读了这篇文章,它避免了必须使用带有在 bean 中定义的 destroy-method=close 参数的 dataSource 配置,如下所示:

    <bean id="SnpjDataSource" class="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean" destroy-method="close">
      <property name="uniqueResourceName" value="@#$$datasource"/>
      <property name="driverClassName" value="com.ibm.as400.access.AS400JDBCDriver"/>
      <property name="url" value="jdbc:as400://VIPER/******"/>
      <property name="user" value="FuManChu"/>
      <property name="password" value="*%$@^%$*#^$@^$@"/>
      <property name="maxPoolSize" value="10"/>
      <property name="reapTimeout" value="40"/>
    </bean> 

编辑2:

ConnectionRecycler.recycleConnection 方法:

public static void recycleConnection(Statement state, boolean closeConnection, 
        Connection connect) {
    try {
        state.close();
        if (closeConnection) {
            connect.close();
        }
    } catch (SQLException sqlEx) {
        logger.error("Error closing resources!  ", sqlEx);
    }
}
4

1 回答 1

0

这取决于您的数据源。如果您想确定使用相同的连接,请在#getConnection调用中保留对它的句柄或使用SingleConnectionDataSource。请注意,您必须在线程安全的环境中操作才能使用此数据源。它本身不是线程安全的。

此外,您实际上不需要Connection直接访问。这就是JdbcTemplate. 它隐藏了 JDBC 内部......避免了泄漏连接等的风险。

于 2013-04-23T15:30:22.690 回答