spring注解事务及事务回滚失败的原因

背景

spring支持编程式事务管理和声明式事务管理两种方式。

编程式事务管理使用TransactionTemplate或者直接使用底层的PlatformTransactionManager。对于编程式事务管理,spring推荐使用TransactionTemplate。

声明式事务管理建立在AOP之上的。其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。

声明式事务管理也有两种常用的方式,一种是基于tx和aop名字空间的xml配置文件,另一种就是基于@Transactional注解。显然基于注解的方式更简单易用,更清爽。

自动提交(AutoCommit)与连接关闭时的是否自动提交

自动提交

默认情况下,数据库处于自动提交模式。每一条语句处于一个单独的事务中,在这条语句执行完毕时,如果执行成功则隐式的提交事务,如果
执行失败则隐式的回滚事务。

spring注解事务的实现

maven创建一个普通项目,当然web项目也可以,我这里是一个web项目
pom.xm如下,本身是用不到这么多jar,直接从项目中拷贝的,懒得删。

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>com.bamboogroupId>
  <artifactId>anoTestartifactId>
  <packaging>warpackaging>
  <version>0.0.1-SNAPSHOTversion>
  <name>anoTest Maven Webappname>
  <url>http://maven.apache.orgurl>

    <repositories>
        <repository>
            <id>nexus_publicid>
            <name>nexus_publicname>
            <url>http://repo.maven.apache.org/maven2/url>
            <releases>
                <enabled>trueenabled>
            releases>
            <snapshots>
                <enabled>falseenabled>
            snapshots>
        repository>
    repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>nexus_publicid>
            <name>nexus_publicname>
            
            <url>http://repo.maven.apache.org/maven2/url>
            <layout>defaultlayout>
            <snapshots>
                <enabled>falseenabled>
            snapshots>
            <releases>
                <updatePolicy>neverupdatePolicy>
            releases>
        pluginRepository>
    pluginRepositories>



    
    <properties>
        
        <spring.version>4.1.0.RELEASEspring.version>
        <shiro.version>1.2.3shiro.version>
        <mybatis.version>3.2.8mybatis.version>
        <mybatis-spring.version>1.2.2mybatis-spring.version>
        <mysql.version>5.1.26mysql.version>
        <druid.version>1.0.9druid.version>
        <junit.version>3.8.1junit.version>
        <log4j.version>1.2.17log4j.version>
        <slf4j.version>1.7.5slf4j.version>
        <poi.version>3.10-FINALpoi.version>
        <commons-lang3.version>3.1commons-lang3.version>
        <commons-io.version>2.4commons-io.version>
        <commons-codec.version>1.8commons-codec.version>
        <commons-fileupload.version>1.3.1commons-fileupload.version>
        <commons-beanutils.version>1.8.3commons-beanutils.version>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <jdk.version>1.7jdk.version>
    properties>


<dependencies>
    
    
        <dependency>
            <groupId>org.apache.tomcatgroupId>
            <artifactId>servlet-apiartifactId>
            <version>6.0.37version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-coreartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-ormartifactId>
            <version>${spring.version}version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>${spring.version}version>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>${spring.version}version>
        dependency>

        
        <dependency>
            <groupId>aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.5.4version>
        dependency>

        
        <dependency>
            <groupId>javax.injectgroupId>
            <artifactId>javax.injectartifactId>
            <version>1version>
        dependency>

        
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.16version>
        dependency>
        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.21version>
        dependency>
        <dependency>
            <groupId>org.codehaus.jacksongroupId>
            <artifactId>jackson-mapper-aslartifactId>
            <version>1.9.13version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>3.8.1version>
            <scope>testscope>
        dependency>

        
            <dependency>  
                <groupId>com.fasterxml.jackson.coregroupId>  
                <artifactId>jackson-coreartifactId>  
                <version>2.1.0version>  
            dependency>  
            <dependency>  
                <groupId>com.fasterxml.jackson.coregroupId>  
                <artifactId>jackson-databindartifactId>  
                <version>2.1.0version>  
            dependency>  
            <dependency>  
                <groupId>com.fasterxml.jackson.coregroupId>  
                <artifactId>jackson-annotationsartifactId>  
                <version>2.1.0version>  
            dependency>   
        
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-coreartifactId>
            <version>${shiro.version}version>
        dependency>
        
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-webartifactId>
            <version>${shiro.version}version>
        dependency>
        
        <dependency>
            <groupId>org.apache.shirogroupId>
            <artifactId>shiro-springartifactId>
            <version>${shiro.version}version>
        dependency>
        
        <dependency>
            <groupId>commons-dbcpgroupId>
            <artifactId>commons-dbcpartifactId>
            <version>1.4version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId> 
            <version>${mybatis.version}version>
        dependency>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>${mybatis-spring.version}version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>${mysql.version}version>
        dependency>
        
        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>${commons-io.version}version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>${commons-fileupload.version}version>
        dependency>
    
        <dependency>
            <groupId>commons-beanutilsgroupId>
            <artifactId>commons-beanutilsartifactId>
            <version>1.8.3version>
            <type>jartype>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
            <version>3.1version>
            <type>jartype>
            <scope>compilescope>
        dependency>
        
        <dependency>
            <groupId>opensymphonygroupId>
            <artifactId>sitemeshartifactId>
            <version>2.4.2version>
        dependency>
        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

        
        <dependency>
            <groupId>net.sf.ehcachegroupId>
            <artifactId>ehcache-coreartifactId>
            <version>2.8.3version>
        dependency>
        
        






  dependencies>
  <build>
    <finalName>onedollarfinalName>
  build>
project>

spring.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
     xmlns:cache="http://www.springframework.org/schema/cache"
     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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/cache  http://www.springframework.org/schema/cache/spring-cache.xsd
    http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

       
    <context:component-scan base-package="anotest" />  

      
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://127.0.0.1/shiro" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="initialSize" value="3" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
        <property name="minIdle" value="2" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="validationQuery" value="select 1" />
        <property name="timeBetweenEvictionRunsMillis" value="20000" />
        <property name="numTestsPerEvictionRun" value="100" />
    bean>

        
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
          
        <property name="mapperLocations" value="classpath:anotest/mapper/*.xml">property>  
        <property name="typeAliasesPackage" value="anotest" />
    bean>  

        
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="anotest.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>  
    bean>  





      
    <bean id="txManager"  
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
            p:dataSource-ref="dataSource">  
    bean>  

      
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" /> 

    
    

    
    


beans>

代码片段

创建包名
anotest.dao
anotest.mapper
anotest.service.impl

LogDao.java

package anotest.dao;

import anotest.Log;


/**
 * log页面表 数据库处理类
 */
public interface LogDao {

    void add(Log log);
}

LogMapper.xml



<mapper namespace="anotest.dao.LogDao">

<resultMap type="Log" id="Log">
    <id column="LOG_ID" property="logId" javaType="java.lang.Long" jdbcType="BIGINT"/>
    <result column="IMEI_CODE" property="imeiCode" javaType="java.lang.String" jdbcType="VARCHAR"/>
    <result column="DAY_TIME" property="dayTime" javaType="java.lang.String" jdbcType="VARCHAR"/>
resultMap>



<sql id="AllColumnlist">
LOG_ID,IMEI_CODE,DAY_TIME
sql>


<sql id="CommonColumnlist">
LOG_ID,IMEI_CODE,DAY_TIME
sql>

<insert id="add" parameterType="Log" useGeneratedKeys="true" keyProperty="LogId">
    insert into T_LOG (
        <if test="logId!=null">
        LOG_ID,
        if>
        IMEI_CODE,
        DAY_TIME
    ) values (
        <if test="logId!=null">
        #{logId,jdbcType = BIGINT},
        if>
        #{imeiCode,jdbcType = VARCHAR},
        #{dayTime,jdbcType = VARCHAR}
    )
insert>


<delete id="delete">
    delete from T_LOG 
    <where>
        Log_ID=#{0}
    where>
delete>

<select id="get" resultMap="Log">
    select <include refid="AllColumnlist"/> from T_LOG
    <where>
        LOG_ID=#{0}
    where>
select>


<select id="getLogByCode" parameterType="java.lang.String" resultMap="Log">
    select * from T_LOG
    <where>
        IMEI_CODE=#{0}
    where>
select>


mapper>

Log.java

package anotest;


public class Log {

    private static final long serialVersionUID = 1l;

    /*Auto generated properties start*/

    //log-id
    private Long logId;
    //IMEI编号
    private String imeiCode;
    //年月日
    private String dayTime;

    /*Auto generated methods start*/


    public Log() {
    }



    /**
     * @param imeiCode
     * @param dayTime
     */
    public Log(String imeiCode, String dayTime) {
        super();
        this.imeiCode = imeiCode;
        this.dayTime = dayTime;
    }








    /*Auto generated methods end*/



    /*Customized methods start*/

    /*Customized methods end*/

    public Long getLogId() {
        return logId;
    }






    public void setLogId(Long logId) {
        this.logId = logId;
    }






    public String getImeiCode() {
        return imeiCode;
    }






    public void setImeiCode(String imeiCode) {
        this.imeiCode = imeiCode;
    }






    public String getDayTime() {
        return dayTime;
    }






    public void setDayTime(String dayTime) {
        this.dayTime = dayTime;
    }






    @Override
    public String toString() {
        return "Log [logId=" + logId + ", imeiCode=" + imeiCode + ", dayTime="
                + dayTime + "]";
    }





}

TestService.java

package anotest.service;

import anotest.Log;


/** 
 * @ClassName: TestService 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author  bamboo   Bamboo
 * @date 2017年3月7日 上午10:17:06 
 * @since
 */

public interface TestService {

    public void addCatch() throws Exception;

    public void addTest();
}

TestServiceImpl.java

package anotest.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import anotest.Log;
import anotest.dao.LogDao;
import anotest.service.TestService;

/** 
 * @ClassName: TestServiceImpl 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author  bamboo   Bamboo
 * @date 2017年3月7日 上午10:38:42 
 * @since
 */
@Service
//默认将类中的所有函数纳入事务管理.    
@Transactional
public class TestServiceImpl implements TestService{

    @Resource
    private LogDao logDao;



    /***
     * 捕获异常后但是不抛出去是无法执行回滚事务的
     * 建议:用本方式写,使上层方法能够检测到数据插入失败,因此必须抛出异常,然后在调用它的方法中捕获异常并提示用户数据提交失败
     * @throws Exception 
     */
    @Transactional
    public void addCatch() throws Exception {
        // TODO Auto-generated method stub

         try {
             SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            String dayTime=format.format(new Date());
            Log log =new Log("ABCD", dayTime);
             log.setLogId(System.currentTimeMillis());
             System.out.println(log.toString());
            // 调用Dao执行插入操作
            logDao.add(log);//正常常数据
            log.setDayTime(dayTime+"yyyyyyyyyyyyyyyyyyy");
            // 调用Dao执行插入操作
            logDao.add(log);//异常数据
        } catch (Exception e) {
            // TODO Auto-generated catch block

            System.out.println("插入失败");
            //throw new Exception(e);//注意:正常环境中必须去掉本行注释,当把这行去掉注释事务回滚就会起作用
        }

    }

    /******
     * 运行时异常不作捕获则则能够正常执行回滚事务
     */
    @Transactional
    public void addTest() {
        // TODO Auto-generated method stub
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String dayTime=format.format(new Date());
        Log log =new Log("ABCD", dayTime);
         log.setLogId(System.currentTimeMillis());
         System.out.println(log.toString());
        // 调用Dao执行插入操作
        logDao.add(log);
        log.setDayTime(dayTime+"yyyyyyyyyyyyyyyyyyy");
        // 调用Dao执行插入操作
        logDao.add(log);//异常数据
    }


}

测试类

ContextConfig.java

import org.junit.runner.RunWith;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  

//指定bean注入的配置文件  
@ContextConfiguration(locations = { "classpath:spring.xml" })  
//使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner  
@RunWith(SpringJUnit4ClassRunner.class) 
public class ContextConfig extends AbstractJUnit4SpringContextTests {

}

TestCase.java

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import anotest.service.TestService;


public class TestCase extends ContextConfig {

    @Autowired  
    private TestService testService;

    @Test
    public void getTimestampTest() throws Exception{  
        testService.addCatch();//1捕获异常的方法,注释掉异常抛出则不会回滚
        testService.addTest();//2没有任何捕获,能够正常回滚
    } 
}

测试结果

当注释掉注释//2所在的行只执行addCatch()方法时

log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Log [logId=1488871162669, imeiCode=ABCD, dayTime=20170307]
插入失败

插入失败,但是我们看数据库,依然会有数据被插入了

mysql> select * from t_log;
+---------------+-----------+------------+
| LOG_ID        | IMEI_CODE | DAY_TIME   |
+---------------+-----------+------------+
| 1488871162669 | ABCD      | 2017-03-07 |
+---------------+-----------+------------+
1 row in set (0.00 sec)

当注释掉注释//1所在的行只执行addTest()方法时
OUTPUT:

log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Log [logId=1488871460315, imeiCode=ABCD, dayTime=20170307]

看数据库,显然数据没有被插入,而是发生了回滚

mysql> select * from t_log;
+---------------+-----------+------------+
| LOG_ID        | IMEI_CODE | DAY_TIME   |
+---------------+-----------+------------+
| 1488871162669 | ABCD      | 2017-03-07 |
+---------------+-----------+------------+
1 row in set (0.00 sec)

我们在回到addCatch()方法,把下面这行的注释去掉

//throw new Exception(e);//注意:正常环境中必须去掉本行注释,当把这行去掉注释事务回滚就会起作用

运行测试

OUTPUT:

log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Log [logId=1488871709355, imeiCode=ABCD, dayTime=20170307]
插入失败

查看表数,可以看到这次数据并没有被插入

mysql> select * from t_log;
+---------------+-----------+------------+
| LOG_ID        | IMEI_CODE | DAY_TIME   |
+---------------+-----------+------------+
| 1488871162669 | ABCD      | 2017-03-07 |
+---------------+-----------+------------+
1 row in set (0.00 sec)

结论

spring的事务只有在触发运行时异常时才会发生回滚,并且这个异常是在切面中是可以被事务管理器捕获到的,如果我们自己在方法体中捕获而不把这个异常抛出(不通知事务管理器)它就不会除非事务回滚。因此在dao层基本不处理数据库插入异常。

其他原因

mysql数据库引擎的问题
mysql数据库引擎分为两种
innodb:支持事务和索引
myisam:不支持事务和索引,因此这种类型的引擎即使你的代码写的是正确的但是依然不会触发事务回滚。

配置文件扫描的问题
因为spring的容器(applicationContext)和springMVC的(applicationContext)是不同的。

spring容器加载得时候,优先加载ServletContextListener(对应spring.xml)产生的父容器,而springMVC(对应springMVC.xml)产生的是子容器。子容器Controller进行扫描装配时装配的@Service注解的实例是没有经过事务加强处理,

即没有事务处理能力的Service。而父容器进行初始化的Service是保证事务的增强处理能力的。如果不在子容器中将Service除去掉,此时得到的将是原样的无事务处理能力的Service。

所以,我们应把扫描Service的工作放在spring.xml中。让Service和事务注解存在于同一个容器中,这样配置的事务注解就能起作用了。也就是说把这个配置从

springMVC.xml中移到spring.xml的配置中。事务不回滚的问题就能解决了。

本demo下载

http://download.csdn.net/detail/zjcjava/9773010

你可能感兴趣的:(spring,spring)