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">,再重启服务器测试,如果能够顺利通过,则三大框架整合成功。

  

  

原文地址:https://www.cnblogs.com/clear5/p/4354293.html