c3p0是一个开源的jdbc连接池,hibernate 默认支持该数据源
jar文件:
c3p0-0.9.2-pre5.jar
mchange-commons-java-0.2.3.jar
基本示例:
package com.my.c3p0;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0Util {
private static ComboPooledDataSource dataSource;
static{
try {
dataSource = new ComboPooledDataSource();
// 基本4项
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUser("root");
dataSource.setPassword("1234");
// 其他项
// 最大连接数
dataSource.setMaxPoolSize(50);
// 最小连接数
dataSource.setMinPoolSize(10);
// 每次增长的个数
dataSource.setAcquireIncrement(5);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
}
基于XML配置文件的示例:
XML文件(c3p0-config.xml):
<c3p0-config>
<!-- 默认配置,如果没有指定则使用这个配置 -->
<default-config>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
<user-overrides user="test-user">
<property name="maxPoolSize">10</property>
<property name="minPoolSize">1</property>
<property name="maxStatements">0</property>
</user-overrides>
</default-config>
<!-- 命名的配置 -->
<named-config name="myDataSource">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8</property>
<property name="user">root</property>
<property name="password">1234</property>
<!-- 如果池中数据连接不够时一次增长多少个 -->
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">20</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">40</property>
<property name="maxStatements">0</property>
<property name="maxStatementsPerConnection">5</property>
</named-config>
</c3p0-config>
Java代码:
package com.my.c3p0;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0Util2 {
private static ComboPooledDataSource dataSource;
static{
dataSource = new ComboPooledDataSource("myDataSource"); //c3p0-config.xml <named-config name="myDataSource"> 配置名称
}
public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
}
}