另外,你可以使用静态工厂类 com.mchange.v2.c3p0.DataSources 来从传统的JDBC驱动里创建没有池的数据源,然后用这个数据源来构造一个池化了的数据源:DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb", "swaldman", "test-password"); DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled );
// The DataSource ds_pooled is now a fully configured and usable pooled DataSource.
// The DataSource is using a default pool configuration, and Postgres' JDBC driver
// is presumed to have already been loaded via the jdbc.drivers system property or an
// explicit call to Class.forName("org.postgresql.Driver") elsewhere. ...
如果你使用这个数据源工厂类,并且你想编程式地覆盖默认的配置,你可以提供一个 map 来覆盖属性:[code]DataSource ds_unpooled = DataSources.unpooledDataSource(“jdbc:postgresql://localhost/testdb”, “swaldman”, “test-password”); Map overrides = new HashMap();
overrides.put(“maxStatements”, “200”); //Stringified property values work
overrides.put(“maxPoolSize”, new Integer(50)); //“boxed primitives” also work
// create the PooledDataSource using the default configuration and our overrides ds_pooled = DataSources.pooledDataSource( ds_unpooled, overrides );
// The DataSource ds_pooled is now a fully configured and usable pooled DataSource,
// with Statement caching enabled for a maximum of up to 200 statements and a maximum
// of 50 Connections.
…[/code]如果你使用命名配置,你就可以指定一个命名来配置你的数据源:// create the PooledDataSource using the a named configuration and specified overrides
ds_pooled = DataSources.pooledDataSource( ds_unpooled, "intergalactoAppConfig", overrides );
罕见情况:强制使用认证信息,忽略底层的非池化数据源的配置信息
你可以用DataSource.pooledDataSource( … ) 方法来包装任何数据源,通常这没有什么问题。数据源应该能够通过数据库连接的标准的 user 和 password 属性来自动判别用户名和密码。有些数据源实现没有提供这些属性。通常这也一点儿都不成问题。c3p0如果不能找到默认的认证信息,用户也没有通过 getConnection( user, password ) 方法来指定认证信息的话,c3p0将通过获取默认连接来解决这个问题。
然而,有一些非常罕见的情况,比如非c3p0的非池化数据源提供了一个 user 属性,但是没有提供 password 属性。或者有时你想将数据源池化并覆盖内置的认证信息但又不想修改它的user 和 password 属性。
c3p0提供了overrideDefaultUser 和 overrideDefaultPassword 两个配置属性。如果你通过编程式的或者通过其他任何c3p0的配置机制设定了这些属性,c3p0 PooledDataSources将忽略底层数据源的用户名和密码,转而用这两个配置信息来替代。
REF:
http://cwiki.ossez.com/pages/viewpage.action?pageId=4719789