这是我最近遇到的一些事情。
我对Spring的JdbcTemplate的理解是你可以调用:
JdbcTemplate template = new JdbcTemplate(dataSource);
Connection conn = template.getDataSource().getConnection();它使用传入的数据源从JdbcTemplate返回一个连接。如果我这样做了:
template.getDataSource().getConnection().close(); 这是否只是获得另一个连接并将其关闭,从而创建了一个泄漏的资源,还是获得了它正在使用的连接?
编辑:
我在一个类中编写了两个方法,一个是用老式的低级方法编写JDBC语句(使用连接、语句和ResultSets):
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上阅读了这篇文章,它回避了必须使用dataSource配置,并在bean中定义了destroy-method=closed参数,如下所示:
<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> EDIT2:
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);
}
}发布于 2013-04-23 23:30:23
这取决于您的数据源。如果您希望确保使用相同的连接,请保留来自#getConnection调用的句柄或使用SingleConnectionDataSource。请注意,您必须在线程安全的环境中操作才能使用此数据源。它本身不是线程安全的。
而且,您不应该真的需要直接访问Connection。这就是JdbcTemplate的意义所在。它隐藏了JDBC的内部结构...避免连接泄漏等风险。
https://stackoverflow.com/questions/16173225
复制相似问题