---
title: "spring学习笔记：spring事务管理"
author: "falchion"
date: "2009-11-26T18:00:12Z"
tags: []
slug: "spring-spring"
draft: false
lastmod: "2009-11-26T18:00:12Z"
id: 528389
url: "https://falchion.iteye.com/blog/528389"
---

数据库事务的4个特性：  
原子性(atomic): 都成功或者都失败；  
一致性(consistency):事务操作之后,数据库所处的状态和业务规则是一致的;比如a,b账户相互转账之后，总金额不变；  
隔离性(isolation):操作中的事务不相互影响;  
持久性(durability):事务提交后被持久化到数据库.  
数据并发产生的问题:  
脏读:一个事物a读到了另一个事务b未提交的数据,则b回滚后,a读取的数据无效;  
不可重复读:一个事物a第二次读到了另一个事务b修改的数据;  
幻读:在统计数据的事务a两次统计的数据不一致(因为有其他事务新增数据)  
第一类丢失更新:a事务回滚覆盖了b事务提交的数据;  
第二类丢失更新:a事务覆盖了b事务提交的数据.  
事物隔离级别: READ\_UNCOMMITED, READ\_COMMITED, REPEATABLE\_READ, SERIALIZABLE; 一般情况下READ\_COMMITED足够了.  
spring事务管理相关的接口:  
TransactionDefinition:代表一个事物,描述了事务的隔离级别, 超时时间,事务是否只读, 传播规则等等;  
TransactionStatus:描述事物的状态;  
PlatformTransactionManager:事务管理器接口, 只定义了3个方法:getTransaction()获取事务的状态; commit();rollback();  
事务管理器的实现类有多种,根据具体的持久层框架的不同而不同;  
spring中的事务传播行为的种类:  
PROPAGATION\_REQUIRED: 如果当前没有事务,就创建一个事务;如果已经存在事务,则加入事务;  
PROPAGATION\_SUPPORTS: 如果已经存在事务,则加入事务;如果没有事务,则以非事务的方式执行;  
PROPAGATION\_MANDATORY: 使用当前事务, 如果没有, 则抛出异常;  
PROPAGATION\_REQUIRED\_NEW: 新建事务,如果当前有事务, 则挂起;  
PROPAGATION\_NOT\_SUPPORTED:以非事务的方式执行, 如果当前有事务, 则挂起;  
PROPAGATION\_NEVER:以非事务的方式执行, 如果当前有事务,则抛出异常;  
使用spring声明式的事务管理:  
大多数情况下,事务会放在services层,spring声明式的事务管理中,需要做以下的工作:  
1 把dao,service注入到spring容器(这些dao, service不涉及事务);  
2 需要注入一个transactionManager(它需要dataSource);  
3 通过TransactionProxyFactoryBean为目标对象(需要事务的dao, service等等)提供事务增强,产生增强后的代理对象.  
看代码:  
先添加一个CompanyService,  
view plaincopy to clipboardprint?  
package services;    
import java.util.List;    
import model.Company;    
import dao.hibernate.CompanyDao;    
   
public class CompanyService {    
 private CompanyDao companyDao;    
 public CompanyDao getCompanyDao() {    
  return companyDao;    
 }    
 public void setCompanyDao(CompanyDao companyDao) {    
  this.companyDao = companyDao;    
 }    
 public void insertCompany(Company c){    
  //some security check    
  companyDao.save(c);    
  //some updates    
 }    
 public void deleteCompany(int id){    
  //some security check    
  companyDao.deleteById(id);    
  // some updates    
 }    
 public void updateCompany(Company c){    
  companyDao.save(c);    
 }    
 public List list(){    
  return companyDao.list();    
 }    
}   
package services;  
import java.util.List;  
import model.Company;  
import dao.hibernate.CompanyDao;

public class CompanyService {  
 private CompanyDao companyDao;  
 public CompanyDao getCompanyDao() {  
  return companyDao;  
 }  
 public void setCompanyDao(CompanyDao companyDao) {  
  this.companyDao = companyDao;  
 }  
 public void insertCompany(Company c){  
  //some security check  
  companyDao.save(c);  
  //some updates  
 }  
 public void deleteCompany(int id){  
  //some security check  
  companyDao.deleteById(id);  
  // some updates  
 }  
 public void updateCompany(Company c){  
  companyDao.save(c);  
 }  
 public List list(){  
  return companyDao.list();  
 }  
}

 

它调用dao组件执行crud.事务控制一般都放在这一层.

spring事务管理第一种配置方式：为每个目标bean配置一个代理  
view plaincopy to clipboardprint?  
&lt;bean id="companyDao" class="dao.hibernate.CompanyDaoImpl"&gt;   
 &lt;property name="hibernateTemplate" ref="hibernateTemplate" /&gt;   
&lt;/bean&gt;   
&lt;!-- 需要被增强的bean通常命名为xxxxTarget --&gt;   
&lt;bean id="companyServiceTarget" class="services.CompanyService"&gt;   
 &lt;property name="companyDao" ref="companyDao" /&gt;   
&lt;/bean&gt;   
&lt;!-- 事务管理器 --&gt;   
&lt;bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt;   
 &lt;property name="dataSource" ref="dataSource" /&gt;   
&lt;/bean&gt;   
&lt;!-- 被代理之后的service，它具有事务功能,程序中我们就使用它 --&gt;   
&lt;bean id="companyService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"&gt;   
 &lt;!-- 事务管理器 --&gt;   
 &lt;property name="transactionManager" ref="txManager" /&gt;   
 &lt;!-- 需要被代理的目标 --&gt;   
 &lt;property name="target" ref="companyServiceTarget" /&gt;   
 &lt;!-- optimize可选，true代表使用CGLib, false代表使用jdk proxy --&gt;   
 &lt;property name="optimize" value="true" /&gt;   
 &lt;!-- 事务属性, 顺序：　PROPAGATION, ISOLATION, readOnly, -Exceptions, +Exceptions --&gt;   
 &lt;property name="transactionAttributes"&gt;   
  &lt;props&gt;   
   &lt;prop key="insert\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;   
   &lt;prop key="update\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;   
   &lt;prop key="delete\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;   
   &lt;prop key="list"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;   
   &lt;prop key="search\*"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;   
  &lt;/props&gt;   
 &lt;/property&gt;   
&lt;/bean&gt;   
&lt;bean id="companyDao" class="dao.hibernate.CompanyDaoImpl"&gt;  
 &lt;property name="hibernateTemplate" ref="hibernateTemplate" /&gt;  
&lt;/bean&gt;  
&lt;!-- 需要被增强的bean通常命名为xxxxTarget --&gt;  
&lt;bean id="companyServiceTarget" class="services.CompanyService"&gt;  
 &lt;property name="companyDao" ref="companyDao" /&gt;  
&lt;/bean&gt;  
&lt;!-- 事务管理器 --&gt;  
&lt;bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt;  
 &lt;property name="dataSource" ref="dataSource" /&gt;  
&lt;/bean&gt;  
&lt;!-- 被代理之后的service，它具有事务功能,程序中我们就使用它 --&gt;  
&lt;bean id="companyService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"&gt;  
 &lt;!-- 事务管理器 --&gt;  
 &lt;property name="transactionManager" ref="txManager" /&gt;  
 &lt;!-- 需要被代理的目标 --&gt;  
 &lt;property name="target" ref="companyServiceTarget" /&gt;  
 &lt;!-- optimize可选，true代表使用CGLib, false代表使用jdk proxy --&gt;  
 &lt;property name="optimize" value="true" /&gt;  
 &lt;!-- 事务属性, 顺序：　PROPAGATION, ISOLATION, readOnly, -Exceptions, +Exceptions --&gt;  
 &lt;property name="transactionAttributes"&gt;  
  &lt;props&gt;  
   &lt;prop key="insert\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
   &lt;prop key="update\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
   &lt;prop key="delete\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
   &lt;prop key="list"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;  
   &lt;prop key="search\*"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;  
  &lt;/props&gt;  
 &lt;/property&gt;  
&lt;/bean&gt;  
测试:  
view plaincopy to clipboardprint?  
public class Test {    
 public static void main(String\[] args) throws InterruptedException, SQLException{    
  ApplicationContext c = new ClassPathXmlApplicationContext("spring-test.xml");    
  CompanyService s = (CompanyService)c.getBean("companyService");    
  List list = s.list();    
  System.out.println(list.size());    
  s.insertCompany(new Company("[www.ddd.com","ddd","wuhan](http://www.ddd.com%22,%22ddd%22,%22wuhan)", new Date()));    
}}   
public class Test {  
 public static void main(String\[] args) throws InterruptedException, SQLException{  
  ApplicationContext c = new ClassPathXmlApplicationContext("spring-test.xml");  
  CompanyService s = (CompanyService)c.getBean("companyService");  
  List list = s.list();  
  System.out.println(list.size());  
  s.insertCompany(new Company("[www.ddd.com","ddd","wuhan](http://www.ddd.com%22,%22ddd%22,%22wuhan)", new Date()));  
}}  
 

你会发现，这里的配置和前面讲的spring aop多么的相同，不错，他们的原理都是一样的，如果你没有了解过spring aop, 建议看一下。

通常情况下,service层需要的事务控制的配置大都相同,而且方法名大都是insertXXX, updateXXX, deleteXXX, searchXXX, checkXXX诸如此类,所以我们可以配置一个可复用的事务代理:

spring事务管理第二种配置方式：目标bean共享代理基类  
view plaincopy to clipboardprint?  
&lt;!-- abstract="true"标明它是抽象的 --&gt;   
&lt;bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"&gt;   
 &lt;property name="transactionManager" ref="txManager" /&gt;   
 &lt;!-- target被注释掉 --&gt;   
 &lt;!--property name="target" ref="companyServiceTarget" /--&gt;   
 &lt;property name="transactionAttributes"&gt;     
  &lt;props&gt;   
   &lt;prop key="insert\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;   
   &lt;prop key="update\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;   
   &lt;prop key="delete\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;   
   &lt;prop key="list"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;   
   &lt;prop key="search\*"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;   
  &lt;/props&gt;   
 &lt;/property&gt;   
&lt;/bean&gt;   
&lt;bean id="companyService" parent="baseTransactionProxy"&gt;   
 &lt;property name="target" ref="companyServiceTarget" /&gt;   
&lt;/bean&gt;   
&lt;bean id="otherService" parent="baseTransactionProxy"&gt;   
 &lt;property name="target" ref="otherServiceTarget" /&gt;   
&lt;/bean&gt;   
......   
&lt;!-- abstract="true"标明它是抽象的 --&gt;  
&lt;bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true"&gt;  
 &lt;property name="transactionManager" ref="txManager" /&gt;  
 &lt;!-- target被注释掉 --&gt;  
 &lt;!--property name="target" ref="companyServiceTarget" /--&gt;  
 &lt;property name="transactionAttributes"&gt;  
  &lt;props&gt;  
   &lt;prop key="insert\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
   &lt;prop key="update\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
   &lt;prop key="delete\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;  
   &lt;prop key="list"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;  
   &lt;prop key="search\*"&gt;PROPAGATION\_REQUIRED, readOnly&lt;/prop&gt;  
  &lt;/props&gt;  
 &lt;/property&gt;  
&lt;/bean&gt;  
&lt;bean id="companyService" parent="baseTransactionProxy"&gt;  
 &lt;property name="target" ref="companyServiceTarget" /&gt;  
&lt;/bean&gt;  
&lt;bean id="otherService" parent="baseTransactionProxy"&gt;  
 &lt;property name="target" ref="otherServiceTarget" /&gt;  
&lt;/bean&gt;  
......

虽然我们为需要事务增强的bean配置了代理类,但是难保用户还会直接使用目标对象companyServiceTarget; 可以使用拦截器.

spring事务管理第三种配置方式：使用拦截器

view plaincopy to clipboardprint?  
&lt;!-- 配置一个事务拦截器，他对目标对象有事务增强的作用 --&gt;   
&lt;bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"&gt;   
    &lt;property name="transactionManager" ref="txManager" /&gt;   
    &lt;property name="transactionAttributes"&gt;      
        &lt;props&gt;      
            &lt;prop key="\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;      
        &lt;/props&gt;      
    &lt;/property&gt;      
&lt;/bean&gt;   
&lt;!-- 为目标对象自动创建代理 --&gt;   
&lt;bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"&gt;      
    &lt;property name="beanNames"&gt;   
        &lt;list&gt;      
            &lt;value&gt;companyServiceTarget&lt;/value&gt;   
        &lt;/list&gt;      
    &lt;/property&gt;      
    &lt;property name="interceptorNames"&gt;      
        &lt;list&gt;      
            &lt;value&gt;transactionInterceptor&lt;/value&gt;      
        &lt;/list&gt;      
    &lt;/property&gt;      
&lt;/bean&gt;   
&lt;!-- 配置一个事务拦截器，他对目标对象有事务增强的作用 --&gt;  
&lt;bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"&gt;  
 &lt;property name="transactionManager" ref="txManager" /&gt;  
    &lt;property name="transactionAttributes"&gt;   
        &lt;props&gt;   
            &lt;prop key="\*"&gt;PROPAGATION\_REQUIRED&lt;/prop&gt;   
        &lt;/props&gt;   
    &lt;/property&gt;   
&lt;/bean&gt;  
&lt;!-- 为目标对象自动创建代理 --&gt;  
&lt;bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"&gt;   
    &lt;property name="beanNames"&gt;  
        &lt;list&gt;   
            &lt;value&gt;companyServiceTarget&lt;/value&gt;  
        &lt;/list&gt;   
    &lt;/property&gt;   
    &lt;property name="interceptorNames"&gt;   
        &lt;list&gt;   
            &lt;value&gt;transactionInterceptor&lt;/value&gt;   
        &lt;/list&gt;   
    &lt;/property&gt;   
&lt;/bean&gt;

测试:此时可以直接使用companyServiceTarget.

view plaincopy to clipboardprint?  
public class Test {    
    public static void main(String\[] args) throws InterruptedException, SQLException{    
        ApplicationContext c = new ClassPathXmlApplicationContext("spring-test.xml");    
        //直接使用目标对象    
        CompanyService s = (CompanyService)c.getBean("companyServiceTarget");    
        List list = s.list();    
        System.out.println(list.size());    
        s.insertCompany(new Company("[www.ddd.com","ddd","wuhan](http://www.ddd.com%22,%22ddd%22,%22wuhan)", new Date()));    
}}   
public class Test {  
 public static void main(String\[] args) throws InterruptedException, SQLException{  
  ApplicationContext c = new ClassPathXmlApplicationContext("spring-test.xml");  
  //直接使用目标对象  
  CompanyService s = (CompanyService)c.getBean("companyServiceTarget");  
  List list = s.list();  
  System.out.println(list.size());  
  s.insertCompany(new Company("[www.ddd.com","ddd","wuhan](http://www.ddd.com%22,%22ddd%22,%22wuhan)", new Date()));  
}}

spring事务管理第四种配置方式：使用tx命名空间

view plaincopy to clipboardprint?  
&lt;tx:advice id="txAdvice" transaction-manager="txManager"&gt;   
    &lt;tx:attributes&gt;   
        &lt;tx:method name="insert\*" propagation="REQUIRED" /&gt;   
        &lt;tx:method name="update\*" propagation="REQUIRED" /&gt;   
        &lt;tx:method name="delete\*" propagation="REQUIRED" /&gt;   
        &lt;tx:method name="list" propagation="REQUIRED" read-only="true" /&gt;   
    &lt;/tx:attributes&gt;   
&lt;/tx:advice&gt;   
&lt;aop:config&gt;   
    &lt;aop:pointcut id="interceptorPointCuts"   
        expression="execution(* services.\*Service(..))" /&gt;   
    &lt;aop:advisor advice-ref="txAdvice"   
        pointcut-ref="interceptorPointCuts" /&gt;            
&lt;/aop:config&gt;   
&lt;tx:advice id="txAdvice" transaction-manager="txManager"&gt;  
    &lt;tx:attributes&gt;  
        &lt;tx:method name="insert\*" propagation="REQUIRED" /&gt;  
        &lt;tx:method name="update\*" propagation="REQUIRED" /&gt;  
        &lt;tx:method name="delete\*" propagation="REQUIRED" /&gt;  
        &lt;tx:method name="list" propagation="REQUIRED" read-only="true" /&gt;  
    &lt;/tx:attributes&gt;  
&lt;/tx:advice&gt;  
&lt;aop:config&gt;  
    &lt;aop:pointcut id="interceptorPointCuts"  
        expression="execution(* services.\*Service(..))" /&gt;  
    &lt;aop:advisor advice-ref="txAdvice"  
        pointcut-ref="interceptorPointCuts" /&gt;         
&lt;/aop:config&gt;

但是这种配置就需要把tx, aop的命名空间加入进来了：臭长臭长的。

view plaincopy to clipboardprint?  
&lt;beans xmlns="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)"     
        xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"   
        xmlns:p="[http://www.springframework.org/schema/p](http://www.springframework.org/schema/p)"     
        xmlns:context="[http://www.springframework.org/schema/context](http://www.springframework.org/schema/context)"   
        xmlns:aop="[http://www.springframework.org/schema/aop](http://www.springframework.org/schema/aop)"   
        xmlns:tx="[http://www.springframework.org/schema/tx](http://www.springframework.org/schema/tx)"   
        xsi:schemaLocation="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans) [http://www.springframework.org/schema/beans/spring-beans-2.5.xsd](http://www.springframework.org/schema/beans/spring-beans-2.5.xsd)    
                [http://www.springframework.org/schema/context](http://www.springframework.org/schema/context) [http://www.springframework.org/schema/context/spring-context-2.5.xsd](http://www.springframework.org/schema/context/spring-context-2.5.xsd)    
                [http://www.springframework.org/schema/aop](http://www.springframework.org/schema/aop) [http://www.springframework.org/schema/aop/spring-aop-2.5.xsd](http://www.springframework.org/schema/aop/spring-aop-2.5.xsd)    
                [http://www.springframework.org/schema/tx](http://www.springframework.org/schema/tx) [http://www.springframework.org/schema/tx/spring-tx-2.5.xsd](http://www.springframework.org/schema/tx/spring-tx-2.5.xsd)"&gt;   
......    
&lt;/beans&gt;   
&lt;beans xmlns="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans)"  
  xmlns:xsi="[http://www.w3.org/2001/XMLSchema-instance](http://www.w3.org/2001/XMLSchema-instance)"  
  xmlns:p="[http://www.springframework.org/schema/p](http://www.springframework.org/schema/p)"  
  xmlns:context="[http://www.springframework.org/schema/context](http://www.springframework.org/schema/context)"  
  xmlns:aop="[http://www.springframework.org/schema/aop](http://www.springframework.org/schema/aop)"  
  xmlns:tx="[http://www.springframework.org/schema/tx](http://www.springframework.org/schema/tx)"  
  xsi:schemaLocation="[http://www.springframework.org/schema/beans](http://www.springframework.org/schema/beans) [http://www.springframework.org/schema/beans/spring-beans-2.5.xsd](http://www.springframework.org/schema/beans/spring-beans-2.5.xsd)  
    [http://www.springframework.org/schema/context](http://www.springframework.org/schema/context) [http://www.springframework.org/schema/context/spring-context-2.5.xsd](http://www.springframework.org/schema/context/spring-context-2.5.xsd)  
    [http://www.springframework.org/schema/aop](http://www.springframework.org/schema/aop) [http://www.springframework.org/schema/aop/spring-aop-2.5.xsd](http://www.springframework.org/schema/aop/spring-aop-2.5.xsd)  
    [http://www.springframework.org/schema/tx](http://www.springframework.org/schema/tx) [http://www.springframework.org/schema/tx/spring-tx-2.5.xsd](http://www.springframework.org/schema/tx/spring-tx-2.5.xsd)"&gt;  
......  
&lt;/beans&gt;

spring事务管理第五种配置方式：注解

略...

 

本文来自CSDN博客，转载请标明出处：[http://blog.csdn.net/sunxing007/archive/2009/09/22/4579225.aspx](http://blog.csdn.net/sunxing007/archive/2009/09/22/4579225.aspx)