一步一步学springmvc3+hibernate4+c3p0+mysql集成实例

    2013-05-26 21:28:29   来源:   评论:0 点击:

    一步一步学springmvc3+hibernate4+c3p0+mysql集成实例(代码)spring框架很容易配置hibernate的数据源。hibernate4是在hibernate3上做了很大改变的一个版本, 当前spring提供hibernate4的支持。spring框架除了作为...

    spring框架很容易配置hibernate的数据源。hibernate4是在hibernate3上做了很大改变的一个版本, 当前spring提供hibernate4的支持。spring框架除了作为出色的ioc框架之外,本身的springmvc也是一个 很优秀的轻量级的web框架。springmvc的controller开发完全支持注解,开发controller只需要在controller类 上添加@Controller注解标签。

    在本项目中使用到mysql5.6数据库,c3p0作为数据源。让我们一步一步操作,步骤及代码如下:

    步骤一、mysql的建表语句:

    
    CREATE TABLE `test_table` (
    `id`  int(11) NOT NULL AUTO_INCREMENT ,
    `username`  varchar(50)    ,
    `usercode`  varchar(50)   ,
    PRIMARY KEY (`id`)
    )
    

    步骤二、建立TestTableEntity类:

    package com;
     
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
     
    @Entity
    @Table(name="test_table")
    public class TestTableEntity {
         
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private int id;
         
        private String username;
         
        private String usercode;
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getUsername() {
    		return username;
    	}
    
    	public void setUsername(String username) {
    		this.username = username;
    	}
    
    	public String getUsercode() {
    		return usercode;
    	}
    
    	public void setUsercode(String usercode) {
    		this.usercode = usercode;
    	}
       
    } 
    
    

    步骤三、建立TestTableDAO类:

    package com;
    
     
    import org.hibernate.Session;
    import org.hibernate.SessionFactory; 
    import org.springframework.transaction.annotation.Transactional;
     
    public class TestTableDAO {
         
        private SessionFactory sessionFactory;
             
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
         
        @Transactional(readOnly=false)
        public void add(TestTableEntity entity) {
            Session session = sessionFactory.openSession();
            session.save(entity);
            session.close();       
        }
    }
    
    

    步骤四、建立TestTableController类,使用@Controller注解:

    
    package com;
    
      
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
     
    @Controller
    public class TestTableController {
         
        @Autowired
        TestTableDAO testTableDAO;
         
        @RequestMapping(value="/add", method=RequestMethod.POST)
        public String addPerson(@RequestParam("username") String username
        		, @RequestParam("usercode") String usercode
        		, Model model) {
            TestTableEntity p = new TestTableEntity();
            p.setUsername(username);
            p.setUsercode(usercode);
             
            testTableDAO.add(p);
             
            return "/result.jsp";
        }
    }
    

    步骤五、建立applicationContext.xml文件:

    <!--?xml version="1.0" encoding="UTF-8"?-->
    <beans default-lazy-init="true" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:tx="http://www.springframework.org/schema/tx" 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-3.1.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
    		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd		
    		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
        <!-- 配置扫瞄注解service,controller -->  
    	<description>Spring公共配置 </description>
    	<!-- 定义受环境影响易变的变量 --> 
    	<context:property-placeholder location="classpath:/conf/hibernate/hibernate.properties">
        <!-- 使Spring关注Annotation -->
      <context:annotation-config>  
    	<!-- <aop:aspectj-autoproxy/>-->
      <!-- 让Spring通过自动扫描来查询和管理Bean -->
    	<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    	<context:component-scan base-package="com">
    		<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation">
    	</context:exclude-filter></context:component-scan>
    
    
    	<!-- 数据源配置,使用应用内的DBCP数据库连接池 -->
    <bean class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" id="dataSource">
    		<property name="driverClass" value="${jdbc.driver}">
    		<property name="jdbcUrl" value="${jdbc.url}">
    		<property name="user" value="${jdbc.username}">
    		<property name="password" value="${jdbc.password}">
    		<property name="autoCommitOnClose" value="true">
    		<property name="checkoutTimeout" value="${cpool.checkoutTimeout}">
    		<property name="initialPoolSize" value="${cpool.minPoolSize}">
    		<property name="minPoolSize" value="${cpool.minPoolSize}">
    		<property name="maxPoolSize" value="${cpool.maxPoolSize}">
    		<property name="maxIdleTime" value="${cpool.maxIdleTime}">
    		<property name="acquireIncrement" value="${cpool.acquireIncrement}">
    		<property name="maxIdleTimeExcessConnections" value="${cpool.maxIdleTimeExcessConnections}">
    	</property></property></property></property></property></property></property></property></property></property></property></property></bean>
    
    	
    	<!-- 数据源配置,使用应用服务器的数据库连接池 -->
      <!--<bean id="dataSource1" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:comp/env/Datasource</value>
        </property>
      </bean> --> 
    
    	<!-- Hibernate配置 -->
    	<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
    		<property name="dataSource" ref="dataSource">
    		<property name="packagesToScan" value="com">
    		<property name="hibernateProperties">
    			<props>
    				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
    				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
    				<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProviderr</prop>
    				<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>				
    				<prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache/ehcache-hibernate-local.xml</prop>
    				<prop key="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> 
    				<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> 
           <!-- <prop key="hibernate.cache.use_second_level_cache">true</prop> -->
            <prop key="hibernate.cache.use_query_cache">true</prop> 
            <prop key="jdbc.use_scrollable_resultset">false</prop>
           <!-- <prop key="hibernate.transaction.auto_close_session">false</prop> -->
    			</props>
    		</property> 
    	</property></property></bean>
    	<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate"> 
          <property name="dataSource" ref="dataSource"> 
       </property></bean> 
       <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager">
       
    	 <!-- 配置事务管理器 -->
    	<!-- 事务管理器配置,单数据源事务 混用jdbcTemplage和hibernate事务
    	 要使用org.springframework.orm.hibernate3.HibernateTransactionManager -->
    	<bean class="org.springframework.orm.hibernate4.HibernateTransactionManager" id="transactionManager">
    		<property name="sessionFactory" ref="sessionFactory">
    	</property></bean>
     <bean class="com.TestTableDAO" id="testTableDAO">
        <property name="sessionFactory" ref="sessionFactory">
    </property></bean>
     </tx:annotation-driven></context:annotation-config></context:property-placeholder></beans>
    

    步骤六、设置springmvc的mvc的xml配置文件:

    <!--?xml version="1.0" encoding="UTF-8"?-->
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    
    <!--  启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">  
    </bean>  		 <!-- 对定义包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能  
     自动扫描且只扫描@Controller 该配置文件只加载除表现层之外的所有bean
     通过exclude-filter 把所有 @Controller注解的表现层控制器组件排除 -->
     <!-- 开启controller注解支持   -->
    	<context:component-scan base-package="com" use-default-filters="false">
    		<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation">
    	</context:include-filter></context:component-scan>
    	  
    	<mvc:annotation-driven>
     
    	 <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->  
    	<!-- 定义JSP文件的位置 --> 
    	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix" value="/user/">
    		<property name="suffix" value=".jsp">
    	</property></property></bean>
    
        
    </mvc:annotation-driven></beans>
    
    

    步骤七、设置web.xml配置文件:

    <!--?xml version="1.0" encoding="UTF-8"?-->
    <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
      <display-name></display-name>	 
        <display-name>Spring Hibernate</display-name>
         
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
     
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>  
             
    	<servlet>
    		<servlet-name>springServlet</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>/WEB-INF/classes/spring-mvc.xml</param-value>
    		</init-param>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    	<!--     配置对应以.do结尾的请求 拦截所有以do结尾的请求
      
    	  -->  
    	<servlet-mapping>
    		<servlet-name>springServlet</servlet-name>
    		<url-pattern>*.do</url-pattern>
      
    	</servlet-mapping>
    
         
    </web-app>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    
    
    

    步骤八、hibernate.properties的配置文件

     
    #hibernate settings
    hibernate.show_sql=true
    hibernate.format_sql=true
    hibernate.cache.use_query_cache=true
    hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider 
     
    
    #mysql version database setting
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/mysqldb?useUnicode=true&characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=root
    hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
     
    
    #c3p0\u00e8\u00bf\u009e\u00e6\u008e\u00a5\u00e6\u00b1\u00a0\u00e9\u0085\u008d\u00e7\u00bd\u00ae
    # Time to wait for an open connection before timing out
    # (in milliseconds)
    cpool.checkoutTimeout=5000
    
    # Connection pool size
    cpool.minPoolSize=5
    cpool.maxPoolSize=10
    
    # How long to keep unused connections around(in seconds)
    # Note: MySQL times out idle connections after 8 hours(28,800 seconds)
    # so ensure this value is below MySQL idle timeout
    cpool.maxIdleTime=1200
    
    # How long to hang on to excess unused connections after traffic spike
    # (in seconds)
    cpool.maxIdleTimeExcessConnections=1800
    
    # Acquiring new connections is slow, so eagerly retrieve extra connections
    # when current pool size is reached
    cpool.acquireIncrement=5
    
    

    步骤九、建立jsp页面:

      <meta content="text/html; charset=ISO-8859-1" http-equiv="Content-Type" />
    <title></title>
    <form action="add.do" method="post">
    	First name: <input name="username" type="text" /> Last name: <input name="usercode" type="text" /> <input type="submit" value="Save" /> </form>
    
    

    springmvc3+hibernate4+c3p0+mysql

    相关热词搜索:springmvc hibernate c3p0 mysql

    上一篇:hibernate4+spring3 整合配置sessionFactory
    下一篇:hibernate4不使用hibernate3的AnnotationSessionFactoryBean配置sessionFactory

    分享到: 收藏
    评论排行