3

This is how I create a DataSource with DBCP 1.4 connection factory:

PoolableConnectionFactory factory = new PoolableConnectionFactory(
  new DriverManagerConnectionFactory("jdbc:h2:mem:db", "", ""),
  new GenericObjectPool(null),
  null,
  "SELECT 1",
  false,
  true
);
DataSource src = new PoolingDataSource(factory.getPool());

Works fine, but I don't know how to configure it, with parameters listed here: http://commons.apache.org/dbcp/configuration.html. For example, I need to set testWhileIdle to true.

yegor256
  • 102,010
  • 123
  • 446
  • 597

2 Answers2

5
    Properties props = new Properties();
    props.put("validationQuery", "SELECT 1 from dual;");
    props.put("testWhileIdle","true");

    final ObjectPool connectionPool = new GenericObjectPool(null);
    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectUri, props);
    new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true);
    final PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
Robert
  • 51
  • 1
  • 2
2

BasicDataSource has these attributes, can you switch to use that ?

BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(JDBCDriver);
ds.setUrl(JDBCUrl);
ds.setUsername(JDBCUser);
ds.setPassword(JDBCPassword);
ds.setInitialSize(initSize);
ds.setTestOnBorrow(false);
ds.setTestWhileIdle(true);

...

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
yael alfasi
  • 692
  • 1
  • 4
  • 13
  • setDriverClassName does not seem to work. See my question here: http://stackoverflow.com/questions/16458786/trouble-specifying-driver-class-in-dbcp You seem to be an expert on this issue, can you provide some insight? – RAY May 24 '13 at 07:19