Hibernate5使用c3p0连接池

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

猜你喜欢

转载自blog.csdn.net/qq_42402854/article/details/81463337