在介绍Hibernate事务配置之前仍然要先搭建SSH2环境,在前文《Spring整合Struts2中拦截链与注解的使用 》中已经介绍过了Spring与Struts2的整合,接下来我们集成Hibernate需要做的有两件事情,第一加入Hibernate依赖包,第二是在web.xml文件中进行对Hibernate的相关配置。首先来来看需要加入的Hibernate依赖包:
1.antlr-2.7.6.jar
2.commons-collections-3.1.jar
3.dom4j-1.6.1.jar
4.hibernate-jpa-2.0-api-1.0.1.Final.jar
5.javassist-3.12.0.GA.jar
6.jta-1.1.jar
7.ojdbc14.jar
8.slf4j-api-1.6.1.jar
9.slf4j-nop-1.6.4.jar
10.hibernate3.jar
最后需要加入的jar包是你所使用的数据库的驱动,我使用的是mysql数据库,所以加入mysql驱动包mysql-connector-java-3.1.13-bin.jar(根据你所使用的数据库加入相关驱动jar)。接下来进行各配置文件的相关配置,web.xml文件的配置,配置方式如下:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
- <display-name>SSH2</display-name>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>classpath:config/applicationContext-*.xml</param-value>
- </context-param>
- <filter>
- <filter-name>characterEncoding</filter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- <init-param>
- <param-name>forceEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>characterEncoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>openSession</filter-name>
- <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>openSession</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- <init-param>
- <param-name>config</param-name>
- <param-value>struts-default.xml,struts-plugin.xml,config/struts.xml</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- </web-app>
struts.xml文件的配置内容:
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <constant name="struts.action.extension" value=","></constant>
- <package name="testregist" namespace="/" extends="struts-default">
- <action name="regist" class="registAction">
- <result name="success">/success.jsp</result>
- <result name="error" type="redirect">/error.jsp</result>
- </action>
- </package>
- </struts>
applicationContext-bean.xml文件的配置内容:
- <?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-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" >
- <!-- Spring管理Struts2的Action -->
- <bean name="registAction" class="com.action.UserManagerAction" scope="prototype">
- <property name="userManager" ref="userManager"></property>
- </bean>
- <bean name="userManager" class="com.service.UserManager" scope="prototype">
- <property name="userDao" ref="userDao"></property>
- </bean>
- <bean name="userDao" class="com.dao.impl.UserDaoImpl">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- </beans>
applicationContext-commons文件的配置内容:
- <?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-2.5.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- <!-- 配置sessionFactory的方式 -->
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="configLocation">
- <value>classpath:config/hibernate.cfg.xml</value>
- </property>
- </bean>
- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- <!-- 第一种配置事务的方式 ,tx-->
- <!--
- <tx:advice id="txadvice" transaction-manager="transactionManager">
- <tx:attributes>
- <tx:method name="add*" propagation="REQUIRED" no-rollback-for="com.exception.MyRuntimeException"/>
- <tx:method name="modify*" propagation="REQUIRED" no-rollback-for="com.exception.MyRuntimeException"/>
- <tx:method name="del*" propagation="REQUIRED"/>
- <tx:method name="*" propagation="REQUIRED" read-only="true"/>
- </tx:attributes>
- </tx:advice>
- <aop:config>
- <aop:pointcut expression="execution(* com.dao.*.*(..))" id="daoMethod"/>
- <aop:advisor advice-ref="txadvice" pointcut-ref="daoMethod"/>
- </aop:config>
- -->
- <!-- 第二种配置事务的方式,代理 -->
- <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
- <!-- 使用cglib方式实现动态代理
- <property name="proxyTargetClass" value="true"></property>
- -->
- <property name="transactionManager" ref="transactionManager"></property>
- <property name="transactionAttributes">
- <props>
- <prop key="add*">PROPAGATION_REQUIRED, +RuntimeException</prop>
- <prop key="modify*">PROPAGATION_REQUIRED, +com.exception.MyRuntimeException</prop>
- <prop key="del*">PROPAGATION_REQUIRED</prop>
- <prop key="*">PROPAGATION_REQUIRED, readOnly</prop>
- </props>
- </property>
- </bean>
- <bean id="userDao" parent="transactionProxy">
- <property name="target">
- <!-- 直接写bean来代替ref标签的链接方式 -->
- <bean class="com.dao.impl.UserDaoImpl">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
- </property>
- </bean>
- </beans>
hibernate.cfg.xml文件的配置内容:
- <?xml version="1.0" encoding="ISO-8859-1"?>
- <!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.connection.driver_class">com.mysql.jdbc.Driver</property>
- <property name="hibernate.connection.url">jdbc:mysql://localhost/mytest</property>
- <property name="hibernate.connection.username">root</property>
- <property name="hibernate.connection.password">123456</property>
- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
- <property name="hibernate.show_sql">true</property>
- <property name="hibernate.hbm2ddl.auto">update</property>
- <mapping resource="com/entity/User.hbm.xml"/>
- </session-factory>
- </hibernate-configuration>
以上配置文件除web.xml文件外均存在于src目录下得config文件夹中。
最后是相关Java类的编写(UserDao):
- package com.dao;
- import com.entity.User;
- public interface UserDao {
- public void addUser(User user) throws Exception;
- public void modifyUser(User user);
- public void delUser(String username);
- }
UserDaoImpl类实现UserDao接口:
- package com.dao.impl;
- import org.hibernate.SessionFactory;
- import org.springframework.orm.hibernate3.HibernateTemplate;
- import com.dao.UserDao;
- import com.entity.User;
- import com.exception.MyRuntimeException;
- public class UserDaoImpl extends HibernateTemplate implements UserDao {
- private SessionFactory sessionFactory;
- @Override
- public void addUser(User user) throws Exception {
- this.save(user);
- //throw new Exception();
- throw new RuntimeException();
- }
- @Override
- public void modifyUser(User user) {
- this.update(user);
- throw new MyRuntimeException();
- }
- @Override
- public void delUser(String username) {
- this.delete(this.load(User.class, username));
- }
- public void selectUser() {
- }
- }
两个自定义的异常,MyException和MyRuntimeException:
- package com.exception;
- import java.io.PrintStream;
- import java.io.PrintWriter;
- public class MyException extends Exception {
- @Override
- public void printStackTrace() {
- super.printStackTrace();
- }
- @Override
- public void printStackTrace(PrintStream arg0) {
- super.printStackTrace(arg0);
- }
- @Override
- public void printStackTrace(PrintWriter arg0) {
- super.printStackTrace(arg0);
- }
- }
- package com.exception;
- public class MyRuntimeException extends RuntimeException {
- }
UserManager类,UserManager通过调用UserDaoImpl类的addUser()方法对数据进行持久化:
- package com.service;
- import javax.annotation.Resource;
- import com.dao.UserDao;
- import com.entity.User;
- public class UserManager {
- private UserDao userDao;
- public UserDao getUserDao() {
- return userDao;
- }
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- public void addUser(User user) throws Exception {
- userDao.addUser(user);
- }
- public void modifyUser(User user) {
- userDao.modifyUser(user);
- }
- public void delUser(String username) {
- userDao.delUser(username);
- }
- }
UserManagerAction类,该类介于jsp页面与UserManager类之间,通过接收jsp页面传过来的数据作为调用UserManager类的addUser()方法的参数:
- package com.action;
- import javax.annotation.Resource;
- import com.entity.User;
- import com.opensymphony.xwork2.ActionSupport;
- import com.service.UserManager;
- public class UserManagerAction extends ActionSupport {
- private User user;
- private UserManager userManager;
- public User getUser() {
- return user;
- }
- public void setUser(User user) {
- this.user = user;
- }
- public UserManager getUserManager() {
- return userManager;
- }
- public void setUserManager(UserManager userManager) {
- this.userManager = userManager;
- }
- public String addUser() throws Exception {
- System.out.println("---------UserAction.addUser()-----------");
- userManager.addUser(user);
- return "success";
- }
- public String modifyUser() {
- System.out.println("---------UserAction.modifyUser()-----------");
- userManager.modifyUser(user);
- return "success";
- }
- public String delUser() {
- System.out.println("---------UserAction.delUser()-----------");
- userManager.delUser(user.getUsername());
- return "success";
- }
- @Override
- public String execute() throws Exception {
- return addUser();
- }
- }
User实体类:
- package com.entity;
- import javax.persistence.Column;
- import javax.persistence.Entity;
- import javax.persistence.Id;
- import javax.persistence.Table;
- /**
- *
- * @author yang
- * @hibernate.class table="T_User"
- */
- public class User {
- /**
- * @hibernate.id
- * generator-class="native"
- */
- private int id;
- /**
- * @hibernate.property
- */
- private String username;
- /**
- * @hibernate.property
- */
- private String password;
- /**
- * @hibernate.property
- */
- private int age;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
最后是jsp页面代码:
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <form action="regist">
- 姓名:<input name="user.username" type="text"><br>
- 密码:<input name="user.password" type="password"><br>
- 年龄:<input name="user.age" type="text"><br>
- <input type="submit" value="注册">
- </form>
- </body>
- </html>
http://blog.csdn.net/a1314517love/article/details/17091331
上面是添加整个用户的流程,简单来讲就是regist.jsp页面将页面数据提交到UserManagerAction,通过一系列的调用过程实现数据的持久化。在applicationContext-commons.xml文件中列举了两种配置事务的两种方式,这两种方式总的来讲本质上是一样的,只不过第二种是用代理方式。说到事务这里不得不提一句Spring的回滚机制。Spring对Exception和RuntimeException的处理方式是不一样的,如果是出现的是Exception(包含其子类)Spring会认为其是可修复的异常,这样的异常在默认情况下是不回滚的,而RuntimeException(包含其子类)则会被认为是不可恢复的异常,遇到这样的异常默认情况下是进行回滚的,所以如果我们根据自己的需要,想在抛出Exception的时候也想回滚,或在抛出RuntimeException的时候不想回滚的话就可以在applicationContext-commons.xml文件的事务配置部分配置roll-back-for(针对第一种事务配置方式),或以+,-方式(针对第二种事务配置方式)进行自定义配置即可。