C3p0创建方式
c3p0有3种创建方式(1)直接实例化并配置comboPooledDataSource
bean。(2)使用DataSources工厂类
。(3)实现PoolBackedDataSource
类(abstract类)。即实现自己的DataSource。
一、实例化并配置ComboPooledDataSource
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" ); //loads the jdbc driver
cpds.setJdbcUrl( "jdbc:postgresql://localhost/testdb" );
cpds.setUser("swaldman");
cpds.setPassword("test-password");
// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(5);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(20);
// The DataSource cpds is now a fully configured and usable pooled DataSource
If you obtain a DataSource by instantiating a ComboPooledDataSource
, configure it by simply calling appropriate setter methods offered by that class before attempting a call to getConnection()
.
常用的最直接的方式是实例化ComboPooledDataSource。这是一个JavaBean风格的类,提供一个public,无参的构造器。配置参数至少要求配置jdbcUrl。
c3p0支持以name命名的数据源。ComboPooledDataSource提供一个String的构造器,传入name即可。
ComboPooledDataSource cpds = new ComboPooledDataSource("intergalactoApp");
二、使用DataSources facotry工厂类
另一种方法是通过DataSources工厂类创建unpooled DataSource数据源,并且可通过unpooled DataSource创建pooled DataSource。
DataSource ds_unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/testdb",
"swaldman",
"test-password");
DataSource ds_pooled = DataSources.pooledDataSource( ds_unpooled );
自定义配置项
指定一个Map存放配置项,使用pooledDataSource重载方法。
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 );
为数据源指定名字
pooledDataSource重在方法提供命名name
ds_pooled = DataSources.pooledDataSource( ds_unpooled, "intergalactoApp", overrides );