连接池与Spring,Hibernate结合

        前几篇关于Java连接池的介绍都是基于Java应用的,而我们常用的场景是与Spring和ORM框架结合,下面就利用实例学习一下这方面的配置。


        1.下载相关内容:
        c3p0下载地址:http://sourceforge.net/projects/c3p0/
        Proxool下载地址:http://proxool.sourceforge.net/
        Druid下载地址:http://code.alibabatech.com/mvn/releases/com/alibaba/druid/
        Spring下载地址:http://www.springsource.org/download/community
        Hibernate下载地址:http://www.hibernate.org/downloads.html
        ibatis(mybatis)下载地址:http://code.google.com/p/mybatis/


        这里我们下载并采用的版本是:c3p0-0.9.2.1,proxool-0.9.1,druid-0.2.23,spring-framework-3.2.2,hibernate-4.2.3,mybatis-3.2.2.

 

        2.新建一个web项目,这里以之前举例项目为例,将所需要的相关jar包复制到项目的WEB-INF/lib下,这里就不详细说明各框架的jar包依赖关系了,可以自己百度查下。


        3.新建接口C3P0DAO,DruidDAO,ProxoolDAO,并且添加相同的方法:

/**
* 获取用户信息
* @param usrId
* @return
*/
Object getUsrInfo(Integer usrId);

 
        4.在resource目录下新建c3p0.properties,druid.properties,proxool.properties这三个属性文件,他们分别是几种连接池的详细配置信息。


        5.在resource目录下新建Spring配置文件applicationContext-dataSource.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- spring加载资源文件 -->
	<bean name="propertiesConfig"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>classpath:c3p0.properties</value>
				<value>classpath:proxool.properties</value>
				<value>classpath:druid.properties</value>
				<value>classpath:hibernate.properties</value>
			</list>
		</property>
	</bean>

	<!-- c3p0数据源配置 -->
	<bean id="dataSource_c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 数据库驱动 -->
		<property name="driverClass" value="${c3p0.driverClass}" />
		<!-- 数据库连接url -->
		<property name="jdbcUrl" value="${c3p0.jdbcUrl}" />
		<!-- 数据库用户 -->
		<property name="user" value="${c3p0.user}" />
		<!-- 数据库密码 -->
		<property name="password" value="${c3p0.password}" />
		<!-- 初始化时获取连接数 -->
		<property name="initialPoolSize" value="${c3p0.initialPoolSize}" />
		<!-- 连接池中保留的最小连接数 -->
		<property name="minPoolSize" value="${c3p0.minPoolSize}" />
		<!-- 连接池中保留的最大连接数 -->
		<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
	</bean>

	<!-- Proxool数据源配置 -->
	<bean id="dataSource_proxool" class="org.logicalcobwebs.proxool.ProxoolDataSource">
		<!-- 别名 -->
		<property name="alias" value="${proxool.alias}" />
		<!-- 数据库驱动 -->
		<property name="driver" value="${proxool.driver}" />
		<!-- 数据库连接url -->
		<property name="driverUrl" value="${proxool.driverUrl}" />
		<!-- 数据库用户 -->
		<property name="user" value="${proxool.user}" />
		<!-- 数据库密码 -->
		<property name="password" value="${proxool.password}" />
		<!-- 最少保持的空闲连接数 -->
		<property name="prototypeCount" value="${proxool.prototypeCount}" />
		<!-- 最大连接数 -->
		<property name="maximumConnectionCount" value="${proxool.maximumConnectionCount}" />
		<!-- 最小连接数 -->
		<property name="minimumConnectionCount" value="${proxool.minimumConnectionCount}" />
	</bean>

	<!-- Druid数据源配置 -->
	<bean id="dataSource_druid" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!-- 数据库连接url -->
		<property name="url" value="${druid.url}" />
		<!-- 数据库用户 -->
		<property name="username" value="${druid.username}" />
		<!-- 数据库密码 -->
		<property name="password" value="${druid.password}" />
		<!-- 配置连接池初始化大小 -->
		<property name="initialSize" value="${druid.initialSize}" />
		<!-- 最小空闲连接数 -->
		<property name="minIdle" value="${druid.minIdle}" />
		<!-- 最大连接数 -->
		<property name="maxActive" value="${druid.maxActive}" />
		<!-- 获取连接等待超时的时间,单位:毫秒 -->
		<property name="maxWait" value="${druid.maxWait}" />
	</bean>

</beans>

 

 

        6.配置Hibernate与Spring集成,新建Spring配置文件applicationContext-hibernate.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- c3p0 sessionFactory配置,注意是版本为Hibernate4 -->
	<bean id="sessionFactory_c3p0"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 将c3p0的数据源注入给hibernate使用 -->
		<property name="dataSource" ref="dataSource_c3p0" />
		<property name="mappingResources">
			<list>
				<value>com/test/jdbc/model/User.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
				<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
				<prop key="hibernate.connection.characterEncoding">${hibernate.connection.characterEncoding}</prop>
				<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
				<prop key="hibernate.connection.release_mode">${hibernate.connection.release_mode}</prop>
				<prop key="hibernate.autoReconnect">${hibernate.autoReconnect}</prop>
				<prop key="hibernate.cglib.use_reflection_optimizer">${hibernate.cglib.use_reflection_optimizer}</prop>
			</props>
		</property>
	</bean>
	
	<!-- Druid sessionFactory配置,注意是版本为Hibernate4 -->
	<bean id="sessionFactory_druid"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 将c3p0的数据源注入给hibernate使用 -->
		<property name="dataSource" ref="dataSource_druid" />
		<property name="mappingResources">
			<list>
				<value>com/test/jdbc/model/User.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
				<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
				<prop key="hibernate.connection.characterEncoding">${hibernate.connection.characterEncoding}</prop>
				<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
				<prop key="hibernate.connection.release_mode">${hibernate.connection.release_mode}</prop>
				<prop key="hibernate.autoReconnect">${hibernate.autoReconnect}</prop>
				<prop key="hibernate.cglib.use_reflection_optimizer">${hibernate.cglib.use_reflection_optimizer}</prop>
			</props>
		</property>
	</bean>
	
	<!-- Proxool sessionFactory配置,注意是版本为Hibernate4 -->
	<bean id="sessionFactory_proxool"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<!-- 将c3p0的数据源注入给hibernate使用 -->
		<property name="dataSource" ref="dataSource_proxool" />
		<property name="mappingResources">
			<list>
				<value>com/test/jdbc/model/User.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
				<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
				<prop key="hibernate.connection.characterEncoding">${hibernate.connection.characterEncoding}</prop>
				<prop key="hibernate.connection.autocommit">${hibernate.connection.autocommit}</prop>
				<prop key="hibernate.connection.release_mode">${hibernate.connection.release_mode}</prop>
				<prop key="hibernate.autoReconnect">${hibernate.autoReconnect}</prop>
				<prop key="hibernate.cglib.use_reflection_optimizer">${hibernate.cglib.use_reflection_optimizer}</prop>
			</props>
		</property>
	</bean>
</beans>

 

        7.实现我们之前定义的三个DAO接口,实现类代码比较简单我拿DruidDAOImpl为例,其他类代码相同:

package com.test.jdbc.dao.impl;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.test.jdbc.dao.DruidDAO;
import com.test.jdbc.model.User;

/**
 * DruidDAO实现
 * @author g21121
 *
 */
public class DruidDAOImpl extends HibernateDaoSupport implements DruidDAO {
    
    /**
     * 获取用户信息
     */
    public Object getUsrInfo(Integer usrId) {
        return getHibernateTemplate().get(User.class, usrId);
    }

}

 

       8.新建spring配置文件applicationContext-dao.xml,将三个实现类与spring结合:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<!-- 将c3p0作为数据源的sessionFactory注入 -->
	<bean class="com.test.jdbc.dao.impl.C3P0DAOImpl">
		<property name="sessionFactory" ref="sessionFactory_c3p0" />
	</bean>
	<!-- 将Druid作为数据源的sessionFactory注入 -->
	<bean class="com.test.jdbc.dao.impl.DruidDAOImpl">
		<property name="sessionFactory" ref="sessionFactory_druid" />
	</bean>
	<!-- 将Proxool作为数据源的sessionFactory注入 -->
	<bean class="com.test.jdbc.dao.impl.ProxoolDAOImpl">
		<property name="sessionFactory" ref="sessionFactory_proxool" />
	</bean>

</beans>

        这里我们将之前配置的三个数据源注入到了三个不同命名的sessionFactory,然后将三个sessionFactory分别注入到各自的DAO实现类中,这样就实现了利用不同的数据源来访问数据库。

 

        9.新建一个测试用Servlet,代码如下:

package com.test.jdbc;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.test.jdbc.dao.C3P0DAO;
import com.test.jdbc.dao.DruidDAO;
import com.test.jdbc.dao.ProxoolDAO;

/**
 * 测试Servlet
 * @author g21121
 *
 */
public class UserServlet extends HttpServlet {
    /**
     * 此处利用Spring注解自动注入属性
     */
    @Autowired
    private C3P0DAO c3P0DAO;
    @Autowired
    private DruidDAO druidDAO;
    @Autowired
    private ProxoolDAO proxoolDAO;

    /**
     * 处理Get请求
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out
            .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>User Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        out.println("Druid:"+druidDAO.getUsrInfo(1));
        out.println("c3p0:"+c3P0DAO.getUsrInfo(1));
        out.println("Proxool:"+proxoolDAO.getUsrInfo(1));
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        this.doGet(request, response);
    }

    public UserServlet() {
        super();
    }
}

 

 

       这里采用注解方式注入,可以在spring文件中添加以下内容来支持注解注入:
<!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
 
        最后是项目文件,spring和hibernate包比较大所以没包含在其中。

你可能感兴趣的:(Hibernate)