1. 程式人生 > >spring註解事務及事務回滾失敗的原因

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.0</modelVersion> <groupId>com.bamboo</groupId> <artifactId>anoTest</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version
>
<name>anoTest Maven Webapp</name> <url>http://maven.apache.org</url> <repositories> <repository> <id>nexus_public</id> <name>nexus_public</name> <url>http://repo.maven.apache.org/maven2/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>nexus_public</id> <name>nexus_public</name> <!-- <url>http://repository.jboss.org/nexus/content/repositories/root_repository/maven2/</url> --> <url>http://repo.maven.apache.org/maven2/</url> <layout>default</layout> <snapshots> <enabled>false</enabled> </snapshots> <releases> <updatePolicy>never</updatePolicy> </releases> </pluginRepository> </pluginRepositories> <!-- 專案屬性 --> <properties> <!-- jar 版本設定 --> <spring.version>4.1.0.RELEASE</spring.version> <shiro.version>1.2.3</shiro.version> <mybatis.version>3.2.8</mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> <mysql.version>5.1.26</mysql.version> <druid.version>1.0.9</druid.version> <junit.version>3.8.1</junit.version> <log4j.version>1.2.17</log4j.version> <slf4j.version>1.7.5</slf4j.version> <poi.version>3.10-FINAL</poi.version> <commons-lang3.version>3.1</commons-lang3.version> <commons-io.version>2.4</commons-io.version> <commons-codec.version>1.8</commons-codec.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <commons-beanutils.version>1.8.3</commons-beanutils.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <jdk.version>1.7</jdk.version> </properties> <dependencies> <!-- spring相關包 --> <!-- Spring --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>servlet-api</artifactId> <version>6.0.37</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- 切面jar --> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.4</version> </dependency> <!-- javax提供的annotation,注入的註解jar --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- 日誌架包 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!--springMVC 依賴json解析jar --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.1.0</version> </dependency> <!--Apache Shiro所需的jar包 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <!-- <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>${shiro.version}</version> </dependency> --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <!-- <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-quartz</artifactId> <version>${shiro.version}</version> </dependency> --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <!-- 資料庫連線dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- fileupload的jar --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!-- apache 常用包 --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.1</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- 頁面裝飾 --> <dependency> <groupId>opensymphony</groupId> <artifactId>sitemesh</artifactId> <version>2.4.2</version> </dependency> <!-- jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 快取ehcache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.8.3</version> </dependency> <!-- ehcache快取jar --> <!-- <dependency> <groupId>com.googlecode.ehcache-spring-annotations</groupId> <artifactId>ehcache-spring-annotations</artifactId> <version>1.2.0</version> <type>jar</type> <scope>compile</scope> </dependency> --> </dependencies> <build> <finalName>onedollar</finalName> </build> </project>

spring.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: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" /><!-- initial connections -->
        <property name="maxActive" value="10" /><!-- MAX connections -->
        <property name="maxIdle" value="5" /><!-- MAX idle connections -->
        <property name="minIdle" value="2" /><!-- MIN idle connections -->
        <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>

      <!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自動掃描mapping.xml檔案 -->  
        <property name="mapperLocations" value="classpath:anotest/mapper/*.xml"></property>  
        <property name="typeAliasesPackage" value="anotest" />
    </bean>  

      <!-- DAO介面所在包名,Spring會自動查詢其下的類 -->  
    <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>  

    <!-- enables scanning for @Transactional annotations -->  
    <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true" /> 

    <!-- 配置事物的攔截方式 -->
    <!-- <tx:advice id="transAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />

            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="select*" propagation="SUPPORTS" />
            <tx:method name="query*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice> -->

    <!-- 事物配置掃描包 -->
    <!--  <aop:config  proxy-target-class="true">
        <aop:pointcut expression="execution(* anotest.*impl.*(..))" id="transcationPointcut" />
        <aop:advisor advice-ref="transAdvice" pointcut-ref="transcationPointcut" />
    </aop:config> -->


</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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<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   <a href="mailto:[email protected]?subject=hello,bamboo&body=Dear Bamboo:%0d%0a描述你的問題:">Bamboo</a>
 * @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   <a href="mailto:[email protected]?subject=hello,bamboo&body=Dear Bamboo:%0d%0a描述你的問題:">Bamboo</a>
 * @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");