1. pom.xml 導入hibernate-c3p0 架包
注意: hibernate-c3p0 架包中包含 c3p0 ,則不需要單獨引入 c3p0
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.3.4.Final</version>
</dependency>
2. 配置 c3p0 核心信息
更多配置信息:
<session-factory>
<!-- 數據庫基本信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test_hibernate5</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
<!-- hibernate配置信息 MySQL5指5.0+版本的MySQL -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 配置使用 hibernate-c3p0 連接池的核心信息 -->
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">5</property>
<!-- 連接池裏連接的超時時長 -->
<property name="hibernate.c3p0.timeout">2000</property>
<!--最大緩存多少個statement對象 -->
<property name="hibernate.c3p0.max_statements">10</property>
<!-- 該線程會根據時間差值判斷要不要把超時的連接移除 -->
<property name="hibernate.c3p0.idle_test_period">2000</property>
<!-- 當連接池耗盡時,Hibernate應該向數據庫一次性申請的連接數 -->
<property name="hibernate.c3p0.acquire_increment">10</property>
<property name="hibernate.jdbc.batch_size">30</property>
<property name="hibernate.jdbc.fetch_size">100</property>
<!-- ORM 映射關係 -->
<mapping resource="cn/jq/hibernate5/model/Student.hbm.xml"/>
</session-factory>
3. 測試 Hibernate 是否使用 c3p0 連接池
輸出:com.mchange.v2.c3p0.impl.NewProxyConnection@6f0628de [wrapping: com.mysql.jdbc.JDBC4Connection@797cea6f]
@Test
public void test() {
session.doWork(new Work() {
public void execute(Connection arg0) throws SQLException {
System.out.println(arg0);
}
});
}