Spring(三):Spring整合Hibernate

  • 背景:

  本文主要介绍使用spring-framework-4.3.8.RELEASE与hibernate-release-5.2.9.Final项目整合搭建的过程。

  开发环境简介:

    1)、jdk 1.8

    2)、spring-framework-4.3.8.RELEASE、hibernate-release-5.2.9.Final

  • 引入Spring到新建项目My-SSH中

1)导入Spring的required包到My-SSH项目

  新建java的dynamic web 项目,之后把spring-framework-4.3.8.RELEASE\libs下的发布包(*-4.3.8.RELEASE.jar,只拷贝这一种即可)拷贝到WebContent\WEB-INF\lib下。

  除了spring的开发包外,在运行spring时,必须依赖commons-logging包,因此从http://commons.apache.org/proper/commons-logging/download_logging.cgi下载最新的commons-logging包,解压后把包commons-logging-1.2-bin\commons-logging-1.2\commons-logging-1.2.jar拷贝到WebContent\WEB-INF\lib下。

2)配置WebContent\WEB-INF\web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
 3     version="3.0">
 4     <display-name>My-SSH</display-name>
 5     
 6     <welcome-file-list>
 7         <welcome-file>index.html</welcome-file>
 8         <welcome-file>index</welcome-file>
 9     </welcome-file-list>
10     
11       <!-- 配置启动IOC容器的Listener -->
12     <!-- needed for ContextLoaderListener -->
13     <context-param>
14         <param-name>contextConfigLocation</param-name>
15         <param-value>classpath:applicationContext.xml</param-value>
16     </context-param>
17 
18     <!-- Bootstraps the root web application context before servlet initialization -->
19     <listener>
20         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
21     </listener>
22 </web-app>

3)在My-SSH项目根路径下创建conf(Source Folder)文件夹,并添加spring配置文件applicationContext.xml 

注意:

在新建该文件时,需要设定namespace包括:aop,beans,context,tx。

  • 整合Hibernate到My-SSH项目,并与Spring整合

1)导入Hibernate的required包到My-SSH项目

把Hibernate开发包解压路径hibernate-release-5.2.9.Final\lib\required\下的所有包拷贝到WebContent\WEB-INF\lib下;

把mysql-connector-java-5.1.2-beta-bin.jar开发包拷贝到WebContent\WEB-INF\lib下;

引入C3P0开发包,把hibernate-release-5.2.9.Final\lib\optional\c3p0\下的所有包拷贝到WebContent\WEB-INF\lib下。

2)在My-SSH项目根目录下的conf文件中,新建hibernate配置文件hibernate.cfg.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <!--
 8         把一下配置信息转移到jdbc.properties中。
 9         <property name="hibernate.connection.username">root</property>
10         <property name="hibernate.connection.password">123456</property>
11         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
12         <property name="hibernate.connection.url">jdbc:mysql://localhost/my_ssh</property>
13         -->
14 
15         <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
16         <property name="hibernate.show_sql">true</property>
17         <property name="hibernate.format_sql">true</property>
18         <property name="hibernate.hbm2ddl.auto">update</property>
19         <property name="hibernate.current_session_context_class">thread</property>
20     </session-factory>
21 </hibernate-configuration>

3)在My-SSH项目根目录下的conf文件中,新建jdbc.properties文件

#-----------------------------------------------------
# \u6570\u636E\u5E93\u914D\u7F6E
#-----------------------------------------------------
#\u670D\u52A1\u5668\u5730\u5740
host=127.0.0.1
dbName=my_ssh
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://${host}:3306/${dbName}
jdbc.username=root
jdbc.password=123456

#-----------------------------------------------------
# \u9002\u7528\u4E8Ec3p0\u7684\u914D\u7F6E
#-----------------------------------------------------
#-----------------------------------------------------
# c3p0\u53CD\u7A7A\u95F2\u8BBE\u7F6E\uFF0C\u9632\u6B628\u5C0F\u65F6\u5931\u6548\u95EE\u989828800
#-----------------------------------------------------
#idleConnectionTestPeriod\u8981\u5C0F\u4E8EMySQL\u7684wait_timeout
jdbc.c3p0.testConnectionOnCheckout=false
jdbc.c3p0.testConnectionOnCheckin=true
jdbc.c3p0.idleConnectionTestPeriod=3600
#-----------------------------------------------------
# c3p0\u8FDE\u63A5\u6C60\u914D\u7F6E
#-----------------------------------------------------
#initialPoolSize, minPoolSize, maxPoolSize define the number of Connections that will be pooled.
#Please ensure that minPoolSize <= maxPoolSize.
#Unreasonable values of initialPoolSize will be ignored, and minPoolSize will be used instead.
jdbc.c3p0.initialPoolSize=10
jdbc.c3p0.minPoolSize=10
jdbc.c3p0.maxPoolSize=100
#maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool.
jdbc.c3p0.maxIdleTime=3600
#-----------------------------------------------------
# hibernate\u8FDE\u63A5\u6C60\u914D\u7F6E
#-----------------------------------------------------
hibernate.connection.driverClass=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://${host}:3306/${dbName}
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update

4)通过配置My-SSH项目根目录下的conf下的applicationContext.xml文件,将hibernate集成到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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:jdbc.properties" file-encoding="utf-8" ignore-unresolvable="true" />

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClassName}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="testConnectionOnCheckout" value="${jdbc.c3p0.testConnectionOnCheckout}"></property>
        <property name="testConnectionOnCheckin" value="${jdbc.c3p0.testConnectionOnCheckin}"></property>
        <property name="idleConnectionTestPeriod" value="${jdbc.c3p0.idleConnectionTestPeriod}"></property>
        <property name="initialPoolSize" value="${jdbc.c3p0.initialPoolSize}"></property>
        <property name="minPoolSize" value="${jdbc.c3p0.minPoolSize}"></property>
        <property name="maxPoolSize" value="${jdbc.c3p0.maxPoolSize}"></property>
        <property name="maxIdleTime" value="${jdbc.c3p0.maxIdleTime}"></property>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 数据源dataSource -->
        <property name="dataSource" ref="dataSource" />

        <!-- hibernate的配置方案一  -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <!-- hibernate的配置方案二  -->
        <!-- 
        <property name="hibernateProperties"> 
            <props> 
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> 
                <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.temp.use_jdbc_metadata_defaults">false</prop> 
            </props> 
        </property>
         -->

        <!-- 持久化类的位置方案一,通过包进行扫描 -->
        <property name="mappingLocations" value="classpath:com/dx/ssh/entities/*.hbm.xml"></property>
        <!-- spring的spring.jar的jar包内,在org.springframework.orm.hibernate3.annotation下, 
            有一个AnnotationSessionFactoryBean类,其中有一个属性叫做"packagesToScan", 有个方法叫setpackagesToScan(),
        也就是说我可以再spring里面将这个属性给设定上。 
            packagesToScan是"包扫描"的意思,哪些包spring可以给我们扫描一下,看看有哪些实体类,
        这一项在我们在配置文件中配置hibernate的实体类的时候可以这么配,只要给出具体的扫描范围就可以了, 
        不需要将实体类一个一个的写出来 
        -->
        <!-- 持久化类的位置方案二,通过包进行扫描 -->
        <!-- 
        <property name="packagesToScan"> 
            <list> 
                <value>com.dx.ssh.entities</value> 
            </list> 
        </property> 
        -->
        <!-- 持久化类的位置方案三,通过类进行扫描 -->
        <!-- 
        <property name="annotatedClasses"> 
            <list> 
                <value>com.dx.ssh.entities.Member</value> 
                <value>com.dx.ssh.entities.Log</value> 
            </list> 
        </property> 
        -->
    </bean>
    <!-- 配置Hibernate事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 配置事务异常封装 -->
    <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <!-- 基于数据源的事务管理器 -->
    <!-- 
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean> 
     -->        
    
    <!-- 第一种方式: 注解方式配置事物 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>
  • 测试是否集成成功

在My-SSH项目的src下新建包com.dx.ssh.entities,在包内添加Member及Member.hbm.xml

Member.java

 1 package com.dx.ssh.entities;
 2 
 3 public class Member {
 4     private Integer id;
 5     private String name;
 6 
 7     public Integer getId() {
 8         return id;
 9     }
10 
11     public void setId(Integer id) {
12         this.id = id;
13     }
14 
15     public String getName() {
16         return name;
17     }
18 
19     public void setName(String name) {
20         this.name = name;
21     }
22 }
View Code

Member.hbm.xml

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <!-- Generated 2017-5-5 23:51:42 by Hibernate Tools 3.5.0.Final -->
 5 <hibernate-mapping>
 6     <class name="com.dx.ssh.entities.Member" table="MEMBER">
 7         <id name="id" type="java.lang.Integer">
 8             <column name="ID" />
 9             <generator class="native" />
10         </id>
11         <property name="name" type="java.lang.String">
12             <column name="NAME" />
13         </property>
14     </class>
15 </hibernate-mapping>

运行项目,如果项目启动没有错误,并且在mysql新建的数据my_ssh库中包含表MEMBE,就说明集成成功。

 

posted @ 2017-05-07 18:07  cctext  阅读(870)  评论(0编辑  收藏  举报