1. 程式人生 > >Spring(三):Spring整合Hibernate

Spring(三):Spring整合Hibernate

ng- checkout wait 哪些 check driver eas package class

  • 背景:

  本文主要介紹使用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下;

引入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,就說明集成成功。

Spring(三):Spring整合Hibernate