SSH整合之三:添加Hibernate環境且使之與Spring進行整合


3.添加Hibernate環境,版本:hibernate-distribution-3.6.0.Final

  1)准備mysql(版本5以上),在mysql中創建庫,語句如下:

  create database ssh default character set utf8;

  2)添加jar包:

    拷貝hibernate3.jar到項目的lib下。

    在下載好的框架解壓,然后在lib下面:

    拷貝required下的所有jar包至項目lib下;

    拷貝optional下的c3p0的jar包至項目lib下;

    拷貝jpa下面的jar包至項目lib下;

    拷貝bytecode下面的jar包至項目lib下,如項目中已經有javassist的jar包,則此包不用再拷貝。

    下載mysql的驅動包,並添加到項目的lib下。

  3)在config中創建配置文件hibernate.cfg.xml,如下:  

 1 <!DOCTYPE hibernate-configuration PUBLIC
 2     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 3     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 4 
 5 <hibernate-configuration>
 6     <session-factory name="foo">
 7         <!-- 顯示sql -->
 8         <property name="show_sql">true</property>
 9         <!-- mysql方言 -->
10         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
11         <!-- 自動建表 -->
12         <property name="hbm2ddl.auto">update</property>
13         <!-- 數據庫連接信息
14         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
15         <property name="connection.url">jdbc:mysql:///ssh</property>
16         <property name="connection.username">root</property>
17         <property name="connection.password">root</property> -->
 18 </session-factory> 19 </hibernate-configuration>

  4)在domain中創建一個User的model類,用於測試hibernate環境是否添加成功(我們約定,所有model類統一id類型為Long):

 1 package cn.clear.web.domain;
 2 
 3 public class User {
 4     
 5     private Long id;
 6     private String name;
 7     
 8     public Long getId() {
 9         return id;
10     }
11     public void setId(Long id) {
12         this.id = id;
13     }
14     public String getName() {
15         return name;
16     }
17     public void setName(String name) {
18         this.name = name;
19     }
20     
21 }

  5)同樣在domain層創建與user類對應的User.hbm.xml:

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3         "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5 
 6 <hibernate-mapping package="cn.clear.web.domain">
 7     <class name="User">
 8         <id name="id" type="long">
 9             <generator class="native"/>
10         </id>
11         
12         <property name="name" type="string"  />
13 
14     </class>
15 </hibernate-mapping>

  6)將User.hbm.xml映射到hibernate.cfg.xml中:

    <!-- 映射文件 -->
    <mapping resource="cn/clear/web/domain/User.hbm.xml" />

  7)這樣我們已經添加好了hibernate環境,之所以將hibernate.cfg.xml中的數據庫連接信息注釋掉,是因為我們將會在與Spring整合時放到applicationContext.xml中。

  8)打開applicationContext.xml,配置SessionFactory: 

1 <!-- 配置SessionFactory -->
2     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
3         <!-- 指定hibernate的配置文件 -->
4         <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
5         <!-- 指定dataSource -->
6         <property name="dataSource" ref="dataSource"></property>
7     </bean>

  9)配置c3p0連接池:

 1 <!-- 配置c3p0連接池 -->
 2     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 3         <!-- 數據庫連接信息 -->
 4         <property name="driverClass" value="${driverClass}"></property>
 5         <property name="jdbcUrl" value="${jdbcUrl}"></property>
 6         <property name="user" value="${user}"></property>
 7         <property name="password" value="${password}"></property>
 8         <!-- 其他配置信息 -->
 9         <!--初始化時獲取三個連接,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
10         <property name="initialPoolSize" value="3"></property>
11         <!--連接池中保留的最小連接數。Default: 3 -->
12         <property name="minPoolSize" value="3"></property>
13         <!--連接池中保留的最大連接數。Default: 15 -->
14         <property name="maxPoolSize" value="5"></property>
15         <!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 -->
16         <property name="acquireIncrement" value="3"></property>
17         <!-- 控制數據源內加載的PreparedStatements數量。如果maxStatements與maxStatementsPerConnection均為0,則緩存被關閉。Default: 
18             0 -->
19         <property name="maxStatements" value="8"></property>
20         <!--maxStatementsPerConnection定義了連接池內單個連接所擁有的最大緩存statements數。Default: 0 -->
21         <property name="maxStatementsPerConnection" value="5"></property>
22         <!--最大空閑時間,1800秒內未使用則連接被丟棄。若為0則永不丟棄。Default: 0 -->
23         <property name="maxIdleTime" value="1800"></property>
24     </bean>

  10)在config中添加jdbc.properties文件(注意不要有空格,嚴格按照properties文件的書寫格式):

driverClass = com.mysql.jdbc.Driver
jdbcUrl     = jdbc:mysql:///ssh
user        = root
password    =root

  11)加載jdbc.properties文件:

    <!-- 加載jdbc.properties文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

  12)配置jdbcTemplate,使得在項目中支持JdbcTemplate操作數據庫:

  

     <!-- 配置jdbcTemplate -->
     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
         <property name="dataSource" ref="dataSource"></property>
     </bean>

  13)配置聲明式事務管理:

   <!-- 聲明式事務管理 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

  14)最終applicationContext.xml文件如下所示:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!--
 3   - Middle tier application context definition for the image database.
 4   -->
 5 <beans xmlns="http://www.springframework.org/schema/beans"
 6         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 7         xmlns:context="http://www.springframework.org/schema/context"
 8         xmlns:tx="http://www.springframework.org/schema/tx"
 9         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
10                 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
11                 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
12 
13     <!-- 自動掃描與裝配bean -->
14     <context:component-scan base-package="cn.clear.web"></context:component-scan>
15     
16     <!-- 加載jdbc.properties文件 -->
17     <context:property-placeholder location="classpath:jdbc.properties"/>
18     
19     <!-- 配置c3p0連接池 -->
20     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
21         <!-- 數據庫連接信息 -->
22         <property name="driverClass" value="${driverClass}"></property>
23         <property name="jdbcUrl" value="${jdbcUrl}"></property>
24         <property name="user" value="${user}"></property>
25         <property name="password" value="${password}"></property>
26         <!-- 其他配置信息 -->
27         <!--初始化時獲取三個連接,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
28         <property name="initialPoolSize" value="3"></property>
29         <!--連接池中保留的最小連接數。Default: 3 -->
30         <property name="minPoolSize" value="3"></property>
31         <!--連接池中保留的最大連接數。Default: 15 -->
32         <property name="maxPoolSize" value="5"></property>
33         <!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 -->
34         <property name="acquireIncrement" value="3"></property>
35         <!-- 控制數據源內加載的PreparedStatements數量。如果maxStatements與maxStatementsPerConnection均為0,則緩存被關閉。Default: 
36             0 -->
37         <property name="maxStatements" value="8"></property>
38         <!--maxStatementsPerConnection定義了連接池內單個連接所擁有的最大緩存statements數。Default: 0 -->
39         <property name="maxStatementsPerConnection" value="5"></property>
40         <!--最大空閑時間,1800秒內未使用則連接被丟棄。若為0則永不丟棄。Default: 0 -->
41         <property name="maxIdleTime" value="1800"></property>
42     </bean>
43     
44     <!-- 配置SessionFactory -->
45     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
46         <!-- 指定hibernate的配置文件 -->
47         <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
48         <!-- 指定dataSource -->
49         <property name="dataSource" ref="dataSource"></property>
50     </bean>
51     
52     <!-- 配置jdbcTemplate -->
53     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
54         <property name="dataSource" ref="dataSource"></property>
55     </bean>
56     
57     <!-- 聲明式事務管理 -->
58     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
59         <property name="sessionFactory" ref="sessionFactory"></property>
60         <property name="dataSource" ref="dataSource"></property>
61     </bean>
62     <tx:annotation-driven transaction-manager="transactionManager"/>
63 </beans>

  15)下載添加aopalliance-1.0.jar到lib下,否則在以下測試中會報錯。

  16)在SpringTest.java中添加以下方法測試SessionFactory:

1 //測試SessionFactory
2     @Test
3     public void testSessionFactory() throws Exception {
4         
5         SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");
6         System.out.println(sessionFactory);
7     }

   如果測試通過,則進行下一項。

  17)創建測試事務的類TestService.java,如下:

   

 1 package cn.clear.web.test;
 2 
 3 import javax.annotation.Resource;
 4 
 5 import org.hibernate.Session;
 6 import org.hibernate.SessionFactory;
 7 import org.springframework.stereotype.Service;
 8 import org.springframework.transaction.annotation.Transactional;
 9 
10 import cn.clear.web.domain.User;
11 
12 @Service
13 public class TestService {
14     
15     //通過注解獲取SessionFactory
16     @Resource
17     private SessionFactory sessionFactory;
18     
19     @Transactional//開啟事務
20     public void add2Users() throws Exception {
21         
22 
23         //獲取Session
24         Session session = sessionFactory.getCurrentSession();
25         session.save(new User());
26         //int a = 1/0;//此用於測試事務,如果執行到此,事務回滾,則測試通過,然后注釋此句,看是否成功創建用戶。
27         session.save(new User());
28         
29         
30     }
31 
32 }

  18)在SpringTest.java中創建測試事務的方法,如下:

1 //測試Transaction
2     @Test
3     public void testTransactionManager() throws Exception{
4         // TODO Auto-generated method stub
5         TestService testService = (TestService) ac.getBean("testService");
6         testService.add2Users();
7 
8     }

  然后使用junit進行測試,測試成功后再打開TestService.java里的

  //int a = 1/0的注釋,再重新運行一次,測試回滾。打開數據庫,查看結果。

  id為3的數據因為剛才測試回滾時回滾掉了。

  19)在ActionTest.java中注入TestService.java類,然后啟動WEB服務器進行測試,如果能夠成功進入測試頁面,則環境添加成功。

  20)最后將web.xml內容設置如下:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 5     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 6     <display-name></display-name>
 7     
 8     <!-- 配置Spring的用於初始化容器對象的監聽器 -->
 9     <listener>
10         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
11     </listener>
12     <context-param>
13         <param-name>contextConfigLocation</param-name>
14         <param-value>classpath:applicationContext*.xml</param-value>
15     </context-param>
16 
17     <!-- Struts2過濾器 -->
18     <filter>
19         <filter-name>struts2</filter-name>
20         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
21     </filter>
22 
23     <filter-mapping>
24         <filter-name>struts2</filter-name>
25         <url-pattern>/*</url-pattern>
26     </filter-mapping>
27 
28 
29     <welcome-file-list>
30         <welcome-file>index.jsp</welcome-file>
31     </welcome-file-list>
32 </web-app>

  加上struts2-spring-plugin-2.3.16.3.jar包,並且將struts.xml中的<action name="test" class="cn.clear.web.test.ActionTest">改為<action name="test" class="actionTest">,再重啟服務器測試,如果能夠順利通過,則三大框架整合成功。

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM