struts2+spring+hibernate整合步骤(1)

时间:2022-05-04
本文章向大家介绍struts2+spring+hibernate整合步骤(1),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
struts2、hibernate、spring所需jar包 struts-core-2.x.x.jar ----struts核心包 xwork-core-2.x.x.jar -----身体ruts在其撒很难过构建 ognl-2.6.x.jar ----对象导航语言 freemarker-2.3.x.jar ------struts2的ui标签的模板使用 commons-fileupload-1.2.x.jar ----文件上传组件 2.1.6版本后需加入此文件 struts-spring-plugin-2.x.x.jar ---用于struts2继承spring的插件 hibernate核心安装包下的(下载路径:http://www.hibernate.org/ ,点击Hibernate Core 右边的download) hibernate2.jar libbytecodehibernate-cglib-repack-2.1_3.jar librequired*.jar hibernate安装包下的(下载路径:http://www.hibernate.org/;点击Hibernate Annotations 右边的下载) hibernate-annotations.jar libejb3-persistence.jar、hibernate-commons-annotations.jar hibernate针对JPA的实现包(下载路径:http://www.hibernate.org/ ,点击Hibernate Entitymanager右边下载) hibernate-entitymanager.jar libtestlog4j.jar、 slf4j-log4j12.jar spring安装包下的 distspring.jar libc3p0c3p0-0.9.1.2.jar libaspectiaspectjweaver.jar aspectjrt.jar libcolibcglib-nodep-2.1_3.jar libj2eecommon-annotations.jar vliblog4jlog4j-1.2.15.jar libjakarta-commonscommons_loggin.jar 数据库驱动包 引用 创建mysql数据库ssh 设置编码为utf-8 语句: create database ssh character set 'utf8' collate 'utf8_general_ci' 引用 1.先整合spring和hibernate *将spring和hibernate的jar包放入lib下; *创建spring的beans.xml配置文件

Java代码 copy

1.<?xml version="1.0" encoding="UTF-8"?>    
2.<beans xmlns="http://www.springframework.org/schema/beans" 
3.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
4.    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 
5.    xsi:schemaLocation="http://www.springframework.org/schema/beans   
6.           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd   
7.           http://www.springframework.org/schema/context   
8.           http://www.springframework.org/schema/context/spring-context-2.5.xsd   
9.           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd   
10.           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">   
11.    
12.    <!-- 将bean交由spring管理可以 用<bean></bean>和扫描加注 -->    
13.    <!--    
14.        扫描该包及该包下的子包    
15.    -->    
16.    <context:component-scan base-package="com.yss"></context:component-scan>    
17.    
18.    
19.    <!-- 集成hibernate  sessionFactory单例模式  线程安全  创建耗内存-->    
20.    <!-- 将hibernate的事务也交由spring管理 -->    
21.    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" 
22.        destroy-method="close">    
23.        <property name="driverClass" value="org.gjt.mm.mysql.Driver" />    
24.        <property name="jdbcUrl" 
25.            value="jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8" />    
26.        <property name="user" value="root" />    
27.        <property name="password" value="root" />    
28.        <!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->    
29.        <property name="initialPoolSize" value="1" />    
30.        <!--连接池中保留的最小连接数。-->    
31.        <property name="minPoolSize" value="1" />    
32.        <!--连接池中保留的最大连接数。Default: 15 -->    
33.        <property name="maxPoolSize" value="300" />    
34.        <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->    
35.        <property name="maxIdleTime" value="60" />    
36.        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->    
37.        <property name="acquireIncrement" value="5" />    
38.        <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->    
39.        <property name="idleConnectionTestPeriod" value="60" />    
40.    </bean>    
41.    
42.    <bean id="sessionFactory" 
43.        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">    
44.        <property name="dataSource" ref="dataSource" />    
45.        <property name="mappingResources"><!-- 放置hibernate的配置文件 -->    
46.            <list>    
47.                <value>com/yss/bean/Employee.hbm.xml</value>    
48.            </list>    
49.        </property>    
50.        <property name="hibernateProperties">    
51.            <value>    
52.                hibernate.dialect=org.hibernate.dialect.MySQL5Dialect    
53.                hibernate.hbm2ddl.auto=update    
54.                hibernate.show_sql=true 
55.                hibernate.format_sql=false 
56.              </value>    
57.        </property>    
58.    </bean>    
59.        
60.    <!--hibernate事务管理器配置-->    
61.    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">    
62.        <property name="sessionFactory" ref="sessionFactory"></property>    
63.    </bean>    
64.        
65.    <!--spring可以用xml和注解来配置事务 声明  -->    
66.    <tx:annotation-driven transaction-manager="transactionManager"/>    
67.</beans>    

*配置hibernate的model.hbm.xml和创建model类

*创建service

  1. service接口:

Java代码

1.public interface EmployeeService {    
2.    public boolean save(Employee employee);    
3.    public boolean update(Employee employee);    
4.    public Employee find(String username);    
5.    public boolean delete(String... username);//表示可变参数   
6.    public List<Employee> findAll();    
7.}     

service实现类:

Java代码

1.import java.util.List;    
2.    
3.import javax.annotation.Resource;    
4.    
5.import org.apache.log4j.Logger;    
6.import org.hibernate.SessionFactory;    
7.import org.springframework.stereotype.Service;    
8.import org.springframework.transaction.annotation.Propagation;    
9.import org.springframework.transaction.annotation.Transactional;    
10.    
11.import com.yss.bean.Employee;    
12.import com.yss.service.EmployeeService;    
13.    
14./** 
15. * @author qing 默认bean名称 employeeServiceBean 
16. *@Service @Transactional 注入service和开启事务 
17. */ 
18.@Service 
19.@Transactional 
20.public class EmployeeServiceBean implements EmployeeService {    
21.    private static Logger logger = Logger.getLogger(Employee.class);    
22.    /** 
23.     * 注入sessionFactory 
24.     */ 
25.    @Resource SessionFactory factory;    
26.    
27.    public boolean delete(String... usernames) {    
28.        try {    
29.            for (String username : usernames) {    
30.                factory.getCurrentSession().delete(    
31.                        factory.getCurrentSession().load(Employee.class,    
32.                                username));    
33.            }    
34.        } catch (Exception e) {    
35.            logger.error(e.getMessage());    
36.            return false;    
37.        }    
38.        return true;    
39.    }    
40.    
41.    /* 
42.     * (non-Javadoc) 
43.     *   
44.     * @see com.yss.service.EmployeeService#find(com.yss.bean.Employee) 
45.     * 此标注表示不需要事务处理 
46.     */ 
47.    @Transactional(propagation = Propagation.NOT_SUPPORTED)    
48.    public Employee find(String username) {    
49.        return (Employee) factory.getCurrentSession().get(Employee.class,    
50.                username);    
51.    }    
52.    
53.    @SuppressWarnings("unchecked")    
54.    @Transactional(propagation = Propagation.NOT_SUPPORTED)    
55.    public List<Employee> findAll() {    
56.        return factory.getCurrentSession().createQuery("from Employee emp")  
57.                .list();    
58.    }    
59.    
60.    public boolean save(Employee employee) {    
61.        try {    
62.            factory.getCurrentSession().persist(employee);// .save(employee);//   
63.                                                            // 获取已经开好的Session   
64.        } catch (Exception e) {    
65.            logger.error(e.getMessage());    
66.            return false;    
67.        }    
68.        return true;    
69.    }    
70.    
71.    public boolean update(Employee employee) {    
72.        try {    
73.            factory.getCurrentSession().merge(employee);// 类似于saveOrUpdate()方法   
74.        } catch (Exception e) {    
75.            logger.error(e.getMessage());    
76.            return false;    
77.        }    
78.        return true;    
79.    }    
80.    
81.}