SSHStruts2.3+Spring4.3+Hibernate3整合
Posted sihai_1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSHStruts2.3+Spring4.3+Hibernate3整合相关的知识,希望对你有一定的参考价值。
新建web project工程目录如下图(包括:包结构;配置文件,测试包)
src:(源文件,domain,dao,service,aciton)
test(主要放置junit测试类)
config文件(主要包含配置文件)
目的:以上各文件分类的目的是为了各层之间结构简单,清晰,方便开发者查找!
详细如下图:
第一步:测试SessionFactory.
其一:加入hibernate框架所需的jar包及mysql驱动包;
hibernate3jar包+mysql-connector-java-5.1.7-bin.jar驱动包:
1,未与spring整合前,测试SessionFactory;
1.1 创建数据库:
create database db7;
1.2 在src目录 (cn.lsh.ssh.domain包下)新建实体及所对应的映射文件;
Person.java
//实体
public class Person
private Integer id;//只有id属性
public Person()
public Integer getId()
return id;
public void setId(Integer id)
this.id = id;
person.hbm.xml:
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 实体所对应的映射文件,见名知义 -->
<hibernate-mapping package="cn.lsh.ssh.domain">
<!-- name对应实体,table对应数据库表字段名 -->
<class name="Person" table="person">
<!-- name对应实体中id,column对应表id字段 -->
<id name="id" column="ID" type="integer">
<generator class="native"/>
</id>
</class>
</hibernate-mapping>
1.3 在 config目录下创建hibernate.cfg.xml文件:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 指定数据库以什么方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 配置数据库的基本连接信息 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql:///db6</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 自动更新表结构,如果没有则自动创建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 指定后台显示执行hql语句 -->
<property name="hibernate.show_sql">true</property>
<!-- 加载实体所对应的映射文件 -->
<mapping resource="cn/lsh/ssh/domain/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
1.4 test目录(cn.lsh.ssh.test包下),SpringTest.java
//未整合前单独测试hibernate
@Test
public void testSessionFactory()
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
System.out.println(sessionFactory);
测试,输出结果为:org.hibernate.impl.SessionFactoryImpl@4e0a39de,说明获取sessionFactory成功。
第二步:测试c3p0数据源;
加入spring4.3所需的jar包:
1.1 在 config目录下创建jdbc.properties,beans.xml配置文件:
jdbc.properties
<span style="font-size:14px;">driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:///db7
user=root
password=root</span>
beans.xml中配置如下:
<span style="font-size:14px;"><?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="$driverClass"/>
<property name="jdbcUrl" value="$jdbcUrl"/>
<property name="user" value="$user"/>
<property name="password" value="$password"/>
</bean>
</beans></span>
测试:
//测试c3p0数据源
@Test
public void testDataSource() throws Exception
DataSource dataSource = (DataSource) ac.getBean("dataSource");
System.out.println(dataSource);
System.out.println(dataSource.getConnection());
输出结果为:
com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1br4a2p9i128uyrq1ecwt71|20a29c6e, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1br4a2p9i128uyrq1ecwt71|20a29c6e, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql:///db7, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> user=******, password=******, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
com.mchange.v2.c3p0.impl.NewProxyConnection@3c10e820
说明获取c3p0和数据库连接成功。
第三(整合测试sessionFactory):
beans.xml中配置如下:
<!-- 配sessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
测试:
//整合后测试SessionFactory
@Test
public void testsessionFactory1() throws Exception
//注意:与spring整合后,要从容器中获取sessionFactory
SessionFactory sf = (SessionFactory) ac.getBean("sessionFactory");
System.out.println(sf);
输出结果为:org.hibernate.impl.SessionFactoryImpl@4f1adeb7
说明从容器中获取sessionFactory成功.
第四步:测试事物;
beans.xml中配置如下:
<!-- 配置声明式事物管理器,基于注解的方式 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
1.1 src(cn.lsh.ssh.service)PersonService.java:
package cn.lsh.ssh.service;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.lsh.ssh.domain.Person;
@Service
public class PersonService
@Resource//
private SessionFactory sf;
@Transactional//开启事物
public void add2User()
sf.getCurrentSession().save(new Person());
int i=1/0;//报异常,如果数据回滚,则说明事物开启成功
sf.getCurrentSession().save(new Person());
测试:只输出一条Hibernate: insert into person values ( )语句,说明数据回滚,查看表中没有数据,说明回滚成功。
第五步:单独测试struts;
添加struts2.3所需jar包:
在web.xml中配置struts2的核心过滤器:
<!-- 配置核心过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
1,1 config下新建struts.xml:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts >
<!-- 设为开发模式 -->
<constant name="devMode" value="struts.devMode"/>
<constant name="simple" value="struts.ui.theme"/>
<!-- 配置action扩展名 -->
<constant name="action" value="struts.action.extension"/>
<package name="personAction" namespace="/" extends="struts-default">
<!-- 未与spring整合前class属性写类的全名称,整合后写bean的名称 -->
<action name="test" class="cn.lsh.ssh.controller.personAction" method="execute">
<result name="success" type="dispatcher">/test.jsp</result>
</action>
</package>
</struts>
1,2 src(cn.lsh.ssh.controller)新建PersonAction 继承 ActionSupport:
public class PersonAction extends ActionSupport
private PersonService personService;
//重写execute()方法
public String execute() throws Exception
System.out.println("personAction.execute()");
//personService.add2User();
//返回字符串,默认success.
return "success";
1,3 在WEB-ROOT目录下新建test.jsp:
<body>
success!
</body>
测试:部署,启动服务器,访问:http://localhost:8080/test.action;
如果成功转发的页面成输出 “ success!”则说明配置成功!
第六步:sturts与spring整合:
1,1 添加struts2-spring-plugin-2.1.6.jar
1,2在web.xml中配置springIOC容器监听器:
<!-- 配置springIOC容器监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans*.xml</param-value>
</context-param>
1,3beans.xml,配置
<!-- 自动扫描与装配bean -->
<context:component-scan base-package="cn.lsh.ssh"/>
1,4当与spring整合后修struts.xml中class属性要修改bean的名称,以便让IOC容器来管理bean的对象,这个在struts.xml文件中有详细说明。
1.5,基于注解的方式声明PersonAction为bean的对象:
@Controller
@Scope("prototype")//设为多例
public class PersonAction extends ActionSupport
@Resource//容器注入
private PersonService personService;
//重写execute()方法
public String execute() throws Exception
System.out.println("personAction.execute()");
personService.add2User();//调用service中的add方法,同时开启事物
//返回字符串,默认success.
return "success";
测试:部署,
访问:http://localhost:8080/test.action,如果成功转发的页面成输出 “ success!”,并且查看数据库对应的数据,如果有对应的数据则说明三大框架整合成功!
至此ssh整合成功!
以上是关于SSHStruts2.3+Spring4.3+Hibernate3整合的主要内容,如果未能解决你的问题,请参考以下文章