C3P0连接池在hibernate和spring中的配置

时间:2023-09-04 13:52:32

  首先为什么要使用连接池及为什么要选择C3P0连接池,这里就不多说了,目前C3P0连接池还是比较方便、比较稳定的连接池,能与spring、hibernate等开源框架进行整合。

一、hibernate中使用C3P0连接池

首先在hibernate项目中引入此c3p0相关jar包,我是在hibernate4.2中拿出来的:

C3P0连接池在hibernate和spring中的配置

在hibernate.cfg.xml中配置

<?xml version="1.0" encoding="UTF-8"?>
<!-- <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> -->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property> <!-- 最小连接数 -->
<property name="hibernate.c3p0.min_size">5</property> <!-- 最大连接数 -->
<property name="hibernate.c3p0.max_size">20</property> <!-- 获得连接的超时时间,如果超过这个时间,会抛出异常,单位毫秒 -->
<property name="hibernate.c3p0.timeout">120</property>
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="hibernate.c3p0.max_statements">100</property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="hibernate.c3p0.maxStatementsPerConnection">100</property>
<!-- 每隔120秒检查连接池里的空闲连接 ,单位是秒-->
<property name="hibernate.c3p0.idle_test_period">120</property>
<!-- 当连接池耗尽,且未达到最大连接数时,一次获取的连接数 -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<!--最大空闲时间,25000秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="hibernate.c3p0.maxIdleTime">25000</property> <!--初始化时获取10个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="c3p0.initialPoolSize">10</property>
<!--连接关闭时默认将所有未提交的操作回滚。Default: false -->
<property name="autoCommitOnClose">false</property>
<!--c3p0将建一张名为c3p0_test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么
属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试
使用。Default: null-->
<property name="automaticTestTable">c3p0_test</property>
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts">30</property>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://192.168.162.125:1433;DatabaseName=test</property>
<property name="connection.username">admin</property>
<property name="connection.password">passwd</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property> <mapping resource="com/hibernate/learn/bean/TestBean.hbm.xml" />
</session-factory>
</hibernate-configuration>

与原来的hibernate配置比较可发现在原来的基础上增加了一些配置,如不使用C3P0连接池,则这些新加的配置去掉即可,hibernate默认使用jdbc连接池。java代码的使用与hibernate的使用方法没区别:

Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();

 二、spring中使用C3P0连接池

直接引入C3P0对应的jar包即可,applicationContext.xml中配置数据源的bean

<?xml version="1.0" encoding="UTF-8"?>
<!-- <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true"> <bean id="person" class="com.learn.yt.bean.Person">
<property name="height" value="170"/>
<constructor-arg index="0" ref="skill"/>
</bean> <bean id="skill" class="com.learn.yt.bean.Skill"/> <bean id="dataSource" name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="jdbcUrl" value="jdbc:sqlserver://192.168.162.25:1433;DatabaseName=test_db"/>
<property name="user" value="admin"/>
<property name="password" value="passwd"/>
<property name="maxPoolSize" value="20"/>
<property name="minPoolSize" value="5"/>
<!-- 初始化建立的连接数 -->
<property name="initialPoolSize" value="10"/>
<!-- 最大空闲时间,120秒内未被使用的连接将被丢弃 -->
<property name="maxIdleTime" value="120"/>
<!-- 当连接池耗尽,且未达到最大连接数时,一次获取的连接数 -->
<property name="acquireIncrement" value="2"/>
<!-- 空闲检查时间间隔, 每隔120秒检查连接池里的空闲连接 ,单位是秒-->
<property name="idleConnectionTestPeriod" value="60"/>
</bean> <bean id="dataSource2" name="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="jdbcUrl" value="jdbc:sqlserver://192.168.162.25:1433;DatabaseName=test_db2"/>
<property name="user" value="admin"/>
<property name="password" value="passwd"/>
<property name="maxPoolSize" value="20"/>
<property name="minPoolSize" value="5"/>
<property name="initialPoolSize" value="10"/>
<property name="maxIdleTime" value="120"/>
<property name="acquireIncrement" value="2"/>
<property name="idleConnectionTestPeriod" value="60"/>
</bean>
</beans>

其中的dataSource即为C3P0连接池的配置,可配置多个数据库的连接,bean的id不一样即可。代码中的调用直接获取bean实例,用得到的dataSource对象获取连接即可,如:

 ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource ds = (DataSource)context.getBean("dataSource");
Connection conn = null;
try {
conn = ds.getConnection();
ResultSet res = conn.createStatement().executeQuery("select * from test_hibernate");
while(res.next()){
System.out.println(res.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}