Spring MVC 事务配置
Spring MVC事务配置
要了解事务配置的所有方法,请看一下《Spring事务配置的5种方法》
本文介绍两种配置方法:
一、 XML,使用tx标签配置拦截器实现事务
一、 Annotation方式
以下所使用环境为Spring4.0.3、Hibernate4.3.5
一、 XML,使用tx标签配置拦截器实现事务
Entity类User.java,持久化类,对应数据库表user
package com.lei.demo.entity; import javax.persistence.*; @Entity(name="users")
public class Users { public Users(){
super();
} @Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private Integer id; @Column(name="user_name",length=32)
private String user_name; @Column(name="age")
private Integer age; @Column(name="nice_name",length=32)
private String nice_name; //属性实现...... }
UserDAO.javar,表user的一些操作,其中属性sessionFactory应该由Spring注入,如下:
package com.lei.demo.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository; import com.lei.demo.entity.Users; public class UsersDAO {
private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} public SessionFactory getSessionFactory() {
return sessionFactory;
} public List<Users> getAllUser(){
String hsql="from users";
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(hsql); return query.list();
}
}
UserService.java,业务实现类,如下
package com.lei.demo.service; import javax.annotation.Resource; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import com.lei.demo.dao.*; public class UserService {
private UsersDAO userDao; public int userCount(){
return userDao.getAllUser().size();
} public UsersDAO getUserDao() {
return userDao;
} public void setUserDao(UsersDAO userDao) {
this.userDao = userDao;
} }
首先看一下xml配置,spring-hibernate.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
"> <!-- Hibernate4 -->
<!-- 加载资源文件 其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->
<context:property-placeholder location="classpath:persistence-mysql.properties" /> <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<!-- 可以加多个包 -->
<value>com.lei.demo.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
</props>
</property>
</bean> <!-- 数据库映射 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean> <!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 配置事务异常封装 -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> <!-- 声明式容器事务管理 ,transaction-manager指定事务管理器为transactionManager -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice> <aop:config expose-proxy="true">
<!-- 只对业务逻辑层实施事务 -->
<aop:pointcut id="txPointcut" expression="execution(* com.lei.demo.service..*.*(..))" />
<!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->
<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
</aop:config> </beans>
其中主要配置中是tx:advice和aop:config两个配置节,以Spring AOP的方式实现事务管理。
tx:advice配置了事务的管理者是transactionManager,同时tx:method也规定了如果方法名匹配“add*”和“get*”方法时使用事务,propagation是设定事务的传播级别。除了“add*”和“get*”方法,其他的方法的事务是只读的(典型地,对于只执行查询的事务你会将该属性设为true,如果出现了更新、插入或是删除语句时只读事务就会失败)
aop:config指定了一个aop:pointcut去引用上边的advice。
这样就通过AOP的拦截机制实现了事务,当然你还要用Spring的方式自己配置UserDAO和UserService。
二、 Annotation方式
第一步,首先看一下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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>lei-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/lei-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>lei-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
第二步,spring-hibernate配置,见以下spring-hibernate.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
"> <!-- Hibernate4 -->
<!-- 加载资源文件 其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载-->
<context:property-placeholder location="classpath:persistence-mysql.properties" /> <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<!-- 可以加多个包 -->
<value>com.lei.demo.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
</props>
</property>
</bean> <!-- 数据库映射 -->
<!-- class="org.apache.tomcat.dbcp.dbcp.BasicDataSource" -->
<!-- class="org.springframework.jdbc.datasource.DriverManagerDataSource" -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean> <!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 配置事务异常封装 -->
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> </beans>
第一节中xml配置事务中需要通过配置tx:advice和aop:config来增加事务的功能。此处采用全注释方法,这两个配置节就不需要了。
相应的需要在视图解析配置中启用注释,如下lei-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
"> <!-- 启动自动扫描 该包下所有的Bean(@Controller) -->
<context:component-scan base-package="com.lei.demo" /> <!-- 基于注释的事务,当注释中发现@Transactional时,使用id为“transactionManager”的事务管理器 -->
<!-- 如果没有设置transaction-manager的值,则spring以缺省默认的事务管理器来处理事务,默认事务管理器为第一个加载的事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/> <!-- 定义视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/user/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> </beans>
UserDAO如下
package com.lei.demo.dao; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository; import com.lei.demo.entity.Users; @Repository
public class UsersDAO {
@Resource(name="sessionFactory")
private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} public SessionFactory getSessionFactory() {
return sessionFactory;
} public List<Users> getAllUser(){
String hsql="from users";
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(hsql); return query.list();
}
}
UserService.java如下
package com.lei.demo.service; import javax.annotation.Resource; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import com.lei.demo.dao.*; @Service("userService")
public class UserService {
@Resource
private UsersDAO userDao; @Transactional
public int userCount(){
return userDao.getAllUser().size();
} public UsersDAO getUserDao() {
return userDao;
} public void setUserDao(UsersDAO userDao) {
this.userDao = userDao;
} }
这里,方法名userCount上加入@Transactional,说明这个方法要启用事务。如果类名UserService上加入@Transactional,则表明这个类中的所有方法都会启用事务。
如果配有多个transactionManager,例如配置有transactionManager1,和transactionManager2,则可以通过@Transactional(“transactionManager1”),的方式指定使用哪个数据源的事务。
源代码下载:
http://www.oschina.net/code/snippet_1764868_35775
友情赞助
如果您喜欢此文,感觉对您工作有帮助,预期领导会给您涨工资,不妨小额赞助一下,让我有动力继续努力。
赞助方式1:打开支付宝App,使用“扫一扫”付款,付款码见下图,别忘了付款留言哦!

赞助方式2:支付宝扫一下,领取我的的大红包,并花掉,双方受益

赞助方式3: 如果您有微信钱包,请打开微信,使用“扫一扫”付款,付款码见下图

转载请注明出处!
Spring MVC 事务配置的更多相关文章
- [转]Spring MVC 事务配置
Spring MVC事务配置 要了解事务配置的所有方法,请看一下<Spring事务配置的5种方法> 本文介绍两种配置方法: <tx:advice/>就是告诉事务管理器:怎么做 ...
- Maven 工程下 Spring MVC 站点配置 (三) C3P0连接池与@Autowired的应用
Maven 工程下 Spring MVC 站点配置 (一) Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作 前两篇文章主要是对站点和数据库操作配置进行了演示,如果单 ...
- spring mvc+myBatis配置详解
一.spring mvc Spring框架(框架即:编程注解+xml配置的方式)MVC是Spring框架的一大特征,Spring框架有三大特征(IOC(依赖注入),AOP(面向切面),MVC(建模M- ...
- Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作
详细的Spring MVC框架搭配在这个连接中: Maven 工程下 Spring MVC 站点配置 (一) Maven 工程下 Spring MVC 站点配置 (二) Mybatis数据操作 这篇主 ...
- Maven 工程下 Spring MVC 站点配置 (一)
最近,查找一些具体资料时,虽然会有很多,但是系统的却很少,尤其是对maven 下 spring mvc 站点搭建的配置,总是说的很多但让新手一目了然的步骤却少之又少. 对此闲暇时整理了一下,做了一套较 ...
- Spring mvc系列一之 Spring mvc简单配置
Spring mvc系列一之 Spring mvc简单配置-引用 Spring MVC做为SpringFrameWork的后续产品,Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块 ...
- Spring MVC的配置与DispatcherServlet的分析
Spring MVC是一款Web MVC框架,是目前主流的Web MVC框架之一. Spring MVC工作原理简单来看如下图所示: 接下来进行Spring MVC的配置 首先我们配置Spring M ...
- Spring学习日志之Spring MVC启动配置
对DispatcherServlet进行配置 Spring MVC的配置实际上就是对DispatcherServlet的配置 public class DispatcherServletConfig ...
- Spring MVC的配置和使用
Spring MVC的配置和使用 笔记仓库:https://github.com/nnngu/LearningNotes Spring MVC需要的jar包 文章中 Spring MVC 使用的版本是 ...
随机推荐
- Dynamic CRM 2013学习笔记(四十四)CRM技术支持
有时我们经常遇到一些CRM的问题,一时又无法解决,这时我们可能要找下外援,下面列出一些基本的技术支持. 1. CRM 论坛 https://community.dynamics.com/crm/f ...
- PHP微信墙制作,开源
PHP微信墙制作 微信墙 PHP 注意:由于微信官网不定时会更新,其中模拟登陆以及爬取数据的方式可能会失效,最近这12个月里,就有两次更新导致此功能需要重写. 服务端源码->github地址传送 ...
- 移植到Windows CE 的经验
Windows CE 是微软早期推出的嵌入式设备和移动设备的开发运行平台,虽然目前移动端几乎都是android和ios的天下,但是,在嵌入式设备领域,Windows CE仍然占有一块地盘.很多用户希望 ...
- 基于slideout.js实现的移动端侧边栏滑动特效
HTML5现在本领太大了,PC端已经无法满足它的胃口了,它将强势攻入移动端,所以移动端中各种特效也得基于HTML5实现,看看我们将要介绍的slideout.js,能帮我们实现怎么样的侧边栏滑动特效呢~ ...
- SAFS Distilled --- 9 April 2015 to 16 April 2015
In the org.safs.model, the class Component stores: information of this component's name reference of ...
- Android MonoGame坑记
1.Content 加载声音API错误: 2.TouchPanel.GetState()属于抢占式的,用一次后面不能继续使用,否则状态尚属第一次: 3.TouchPanel 坐标来自于硬件本身: 4. ...
- text-size-adjust属性
在慕课上无意中看到-webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%;这两段代码,居然发现自己完全不理解,然后就去问度娘了,以下是一些 ...
- 《精通移动app测试实战:技术、工具和案例》新书上市
本书是测试专家.性能测试专家.专业畅销书作者--于涌,多年实战经验的总结,涵盖主流的测试工具,包括众多的测试实例,涵盖单元测试.功能测试.性能测试.UI测试.手游测试.自动化测试.测试用例管理.持续集 ...
- 小白学数据分析----->留存率与运营活动分析_I
有关留存率的事情最近扯得比较多,因为在分析数据的时候,越发觉得,分析一定是要来解决问题的,留存率不知何时突然变得流行了,在此讨论留存率倒不是因为流行,而是觉得以留存率为核心,的确是可以帮助我们解决不少 ...
- ListView实现Item局部刷新
对于ListView数据的刷新大家都知道,改变Adapter的数据源,然后调用Adapter的notifyDateSetChanged()方法即可. 但是博主在做公司项目的时候,有个下载模块,因为可 ...