RSS Feed for This PostCurrent Article

iBatis and Apache DBCP Connection Pooling

Download Source

I was using iBatis together with Apache DBCP. Here is the SqlConfig class for iBatis

public class SqlConfig {

private static SqlMapClient sqlMap = null;

static {
try {
String resource = “sqlmap.xml”;
Reader reader = Resources.getResourceAsReader(resource);
sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);

} catch (Exception e) {
// If you get an error at this point, it doesn?t matter what it was. It is going to be
// unrecoverable and we will want the app to blow up hard so we are aware of the
// problem. You should always log such errors and re-throw them in such a way that
// you can be made immediately aware of the problem.
throw new RuntimeException(”Error initializing Cause: ” + e);

* Return SQL map client for SDP schema
* @return
public static SqlMapClient getSqlMapInstance() {
return sqlMap;

This class return the SqlMapClient which can then be used to query, insert, update or delete records from database.

The iBatis configuration file is configured to use Apache DBCP.

<transactionManager type=”JDBC”>
<dataSource type=”DBCP”>
<property name=”driverClassName” value=”${driver}”/>
<property name=”url” value=”${jdbc.url}”/>
<property name=”username” value=”${username}”/>
<property name=”password” value=”${password}”/>

<property name=”initialSize” value=”5″/>
<property name=”maxActive” value=”30″/>
<property name=”maxIdle” value=”20″/>
<property name=”maxWait” value=”60000″/>
<property name=”poolPreparedStatements” value=”true”/>
<property name=”validationQuery” value=”select 0 from dual”/>
<property name=”testOnBorrow” value=”true”/>
<!– <property name=”testWhileIdle” value=”true”/>–>

Due to some integration with legacy system, sometimes I need to get the connection directly from iBatis. I used the following code

try {
SqlMapClient sqlMapClient = SqlConfig.getSqlMapInstance();
Connection conn = sqlMapClient.getDataSource().getConnection();

// After using it, to return it to the connection pool, close it
} catch (SQLException e) {

One thing to take note here, to return the connection to the pool, you can simply call the Connection.close method. If not, you will encounter the following error once the connection pool is exhausted.

org.apache.commons.dbcp.SQLNestedException: Cannot get a connection, pool exhausted
at org.apache.commons.dbcp.PoolingDataSource.
at org.apache.commons.dbcp.BasicDataSource.

Trackback URL

RSS Feed for This PostPost a Comment