如何销毁iBatis连接池?iBatis 2.3.4.726技术问题咨询
Hey there, I’ve worked with iBatis 2.x quite a bit, so let’s walk through how to properly tear down connection pools for your looped creation/destruction testing.
First, it’s important to note that in iBatis 2.3.4, the connection pool is tightly coupled with the SqlMapClient instance. To fully destroy the pool, you’ll need to target both the underlying data source and the SqlMapClient itself. Here’s how to handle different scenarios:
1. Using iBatis’ Built-in Pooled Data Source
If you’re using the default PooledDataSource (configured via <dataSource type="POOLED"> in your SqlMapConfig.xml), you can directly call its forceCloseAll() method to shut down all active connections, then clean up the SqlMapClient instance:
// Get your existing SqlMapClient instance SqlMapClient sqlMapClient = ...; // Access the underlying data source DataSource dataSource = sqlMapClient.getDataSource(); // Force close all connections in the pool if it's the built-in pooled type if (dataSource instanceof PooledDataSource) { ((PooledDataSource) dataSource).forceCloseAll(); } // Now shut down the SqlMapClient itself (uses the implementation class) try { ((SqlMapClientImpl) sqlMapClient).close(); } catch (SQLException e) { // Log or handle the exception as needed for your diagnostics e.printStackTrace(); }
The forceCloseAll() method immediately closes all idle and active connections in the pool, while SqlMapClientImpl.close() cleans up any remaining resources tied to the client.
2. Using Third-Party Connection Pools (e.g., Apache DBCP, C3P0)
If you’re using an external pool like DBCP’s BasicDataSource, you’ll need to call the pool’s native close method first, then clean up the SqlMapClient:
SqlMapClient sqlMapClient = ...; DataSource dataSource = sqlMapClient.getDataSource(); // For Apache DBCP's BasicDataSource if (dataSource instanceof BasicDataSource) { try { ((BasicDataSource) dataSource).close(); } catch (SQLException e) { e.printStackTrace(); } } // Clean up the SqlMapClient try { ((SqlMapClientImpl) sqlMapClient).close(); } catch (SQLException e) { e.printStackTrace(); }
For other pools like C3P0, look for their specific shutdown methods (e.g., ComboPooledDataSource.close()).
Key Notes for Your Diagnostic Loop
- Always pair creation with destruction: Every time you instantiate a
SqlMapClientand its connection pool, make sure to run the above cleanup steps to avoid resource leaks. - Spring integration caveat: If you’re using Spring to manage iBatis, use Spring’s bean lifecycle methods instead. You can call
destroy()on theSqlMapClientbean or useBeanFactory.destroySingletons()to tear down all managed beans (including the data source/pool).
内容的提问来源于stack exchange,提问作者otto

