如何配置DBCP PoolableConnectionFactory?

时间:2011-12-21 18:42:36

标签: java jdbc apache-commons-dbcp

这是我使用DBCP 1.4连接工厂创建数据源的方法:

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

工作正常,但我不知道如何配置它,其中列出了参数:http://commons.apache.org/dbcp/configuration.html。例如,我需要将testWhileIdle设置为true

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

BasicDataSource有这些属性,你能切换到使用吗?

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);

...