Spring 中的事務控制

一、事務控制

  • JavaEE 體系進行分層開發,事務處理位於業務層,Spring 提供了分層設計業務層的事務處理解決方案
  • Spring 框架爲我們提供了一組事務控制的接口。這組接口是在spring-tx-5.0.2.RELEASE.jar 中
  • Spring 的事務控制都是基於 AOP 的,它既可以使用編程的方式實現,也可以使用配置的方式實現

二、事務控制的 API

1、PlatformTransactionManager 接口

此接口是 spring 的事務管理器(平臺事務管理器),它裏面提供了我們常用的操作事務的方法:

  • TransactionStatus getTransaction(TransactionDefinition definition) 獲取事務狀態信息
  • void commit(TransactionStatus status) 提交事務
  • void rollback(TransactionStatus status) 回滾事務

真正的事務管理對象:

  • org.springframework.jdbc.datasource.DataSourceTransactionManager 使用 Spring JDBC 或 MyBatis 進行持久化數據時使用
  • org.springframework.orm.hibernate5.HibernateTransactionManager 使用Hibernate 版本進行持久化數據時使用

2、TransactionDefinition

它是事務的定義信息對象,裏面有如下方法:

  • String getName() 獲取事務對象名稱
  • int getIsolationLevel() 獲取事務的隔離級別
  • int PropagationBehavior() 獲取事務的傳播行爲
  • int getTimeout() 獲取事務的超時時間
  • boolean isReadOnly() 獲取事務是否只讀

3、事務的隔離級別

事務的隔離級別反映了事務提交併發訪問時的處理態度

  • ISOLATION_DEFAULT : 默認級別,歸屬下列某一種
  • ISOLATION_READ_UNCOMMITTED : 可以讀取未提交的數據
  • ISOLATION_READ_COMMITTED : 只能讀取已提交的數據
  • ISOLATION_REPEATABLE_READ : 是否讀取替他事務修改後的數據(MySQL的默認級別)
  • ISOLATION_SERIALAZABLE : 是否讀取替他事務提交添加後的數據

4、事務的傳播行爲

  • REQUIRED:如果當前沒有事務,就新建一個事務,如果已經存在一個事務中,加入到這個事務中。一般的選擇(默認值)
  • SUPPORTS:支持當前事務,如果當前沒有事務,就以非事務方式執行(沒有事務)
  • MANDATORY:使用當前的事務,如果當前沒有事務,就拋出異常
  • REQUERS_NEW:新建事務,如果當前在事務中,把當前事務掛起。
  • NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起
  • NEVER:以非事務方式運行,如果當前存在事務,拋出異常
  • NESTED:如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則執行 REQUIRED 類似的操作。

5、超時時間

默認值是-1,沒有超時限制。如果有,以秒爲單位進行設置

6、TransactionStatus 接口

此接口提供的是事務具體的運行狀態,描述了某個時間點上事務對象的狀態信息方法有:

  • void flush() :刷新事務
  • boolean hasSavePoint() : 獲取事務是否存在存儲點
  • boolean isCompleted() : 獲取事務是否完成
  • boolean isNewTransaction() : 獲取事務是否爲新事務
  • boolean isRollBackOnly() : 獲取事務是否回滾
  • void setRollbackOnly() : 設置事務回滾

三、示例:未開啓事務的轉賬

在這裏插入圖片描述
第一步:封裝 Account.java 實體類來映射數據庫表

package cn.lemon.domain;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "賬戶信息{" +
                "編號=" + id +
                ", 姓名='" + name + '\'' +
                ", 餘額=" + money +
                '}';
    }
}

第二步:新建持久層(dao)接口以及實現類

package cn.lemon.dao;

import cn.lemon.domain.Account;

import java.util.List;

public interface IAccountDao {

    void updateAccount(Account account);

    Account findByIdAccount(Integer accountId);
}
package cn.lemon.dao.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void updateAccount(Account account) {
        try{
            jdbcTemplate.update("update account set name = ?, money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findByIdAccount(Integer accountId) {
        try{
            return jdbcTemplate.queryForObject("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

第三步:新建 applicationContext.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///db_account"></property>
        <property name="username" value="root"></property>
        <property name="password" value="lemon"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dateSource"></property>
    </bean>
    <context:component-scan base-package="cn.lemon"></context:component-scan>
</beans>

第四步:新建業務層(service)接口以及實現類

package cn.lemon.servcie;

public interface IAccountService {
    /**
     * 執行轉賬操作
     * @param inId 轉入的id
     * @param outId 轉出的id
     * @param money 轉入轉出的金額
     */
    void transfer(Integer inId, Integer outId, Double money);
}
package cn.lemon.servcie.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.domain.Account;
import cn.lemon.servcie.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao iAccountDao;

    @Override
    public void transfer(Integer inId, Integer outId, Double money) {
        Account in = iAccountDao.findByIdAccount(inId);
        Account out = iAccountDao.findByIdAccount(outId);

        in.setMoney(in.getMoney() + money);
        iAccountDao.updateAccount(in);

        //int d = 1/0; //模擬異常

        out.setMoney(out.getMoney() - money);
        iAccountDao.updateAccount(out);
    }
}

第五步:測試類

package cn.lemon.servcie.impl;

import cn.lemon.servcie.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/applicationContext.xml")
public class AccountServiceImplTest {
    @Autowired
    private IAccountService iAccountService;

    @Test
    public void testtrnsfer() {
        iAccountService.transfer(1,2,100d);
    }
}

分析結果:
當在第四步的實現類中,開啓異常時,會發生轉賬失敗,也就是id爲1的賬戶增加了100(轉入成功),而id爲2的賬戶卻沒有減少(轉出失敗),這不是我們想要的結果

四、Spring 基於 XML 的事務控制

第一步: 配置事務管理器

    <!--配置事務管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入DataSource-->
        <property name="dataSource" ref="dateSource"></property>
    </bean>

第二步:配置事務的通知引用事務管理器

    <!--配置事務的通知,事務增強-->
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager"></tx:advice>

第三步:配置事務的屬性

        <!--在 tx:advice 標籤內部 配置事務的屬性 -->
        <tx:attributes>
            <tx:method name="transfer" propagation="REQUIRED" read-only="false"/><!--這是轉賬的方法 transfer-->
            <tx:method name="*" propagation="REQUIRED" read-only="true"></tx:method><!--這是除了轉賬之外的其他方法-->
        </tx:attributes>
  • read-only:是否是隻讀事務。默認 false,不只讀。
  • isolation:指定事務的隔離級別。默認值是使用數據庫的默認隔離級別。
  • propagation:指定事務的傳播行爲。
  • timeout:指定超時時間。默認值爲:-1。永不超時。
  • rollback-for:用於指定一個異常,當執行產生該異常時,事務回滾。產生其他異常,事務不回滾。沒有默認值,任何異常都回滾。
  • no-rollback-for:用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時,事務回滾。沒有默認值,任何異常都回滾。

第四步:配置 AOP 切入點表達式

    <!--配置AOP-->
    <aop:config proxy-target-class="true">
        <!--配置切入點表達式-->
        <aop:pointcut id="pointCut" expression="execution(* cn.lemon.service.impl.*.*(..))"></aop:pointcut>
    </aop:config>

第五步:配置切入點表達式和事務通知的對應關係

        <!-- 建立事務的通知和切入點表達式的關係 織入事務增強-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>

完整配置
在這裏插入圖片描述

五、Spring 基於 XML &註解的事務控制

第一步:刪除配置文件 applicationContext.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: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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///db_account?serverTimezone=GMT%2B8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="lemon"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--註解搜索的包-->
    <context:component-scan base-package="cn.lemon"></context:component-scan>
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--
    <tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
        <tx:attributes>
            <tx:method name="transfer"/>
            <tx:method name="*" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>
    <aop:config proxy-target-class="true">
        <aop:pointcut id="pointCut" expression="execution(* cn.lemon.service.impl.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"></aop:advisor>
    </aop:config>
-->
    <!--開啓事務的註解支持-->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager" proxy-target-class="true"></tx:annotation-driven>
</beans>

第二步:在業務層(service)的實現類中使用@Transactional 註解

package cn.lemon.service.impl;

import cn.lemon.dao.IAccountDao;
import cn.lemon.domain.Account;
import cn.lemon.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao iAccountDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void transfer(Integer inId, Integer outId, Double money) {
        Account in = iAccountDao.findByIdAccount(inId);
        Account out = iAccountDao.findByIdAccount(outId);
        in.setMoney(in.getMoney() + money);
        iAccountDao.updateAccount(in);

        //int i = 1/0;//模擬異常

        out.setMoney(out.getMoney() - money);
        iAccountDao.updateAccount(out);
    }
}

六、Spring 基於註解的事務控制

第一步:修改上面的代碼,即:刪除 applicationContext.xml 文件,添加連接數據庫的屬性文件 JdbcConfig.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///db_account?serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=lemon

第二步:寫配置類 SpringConfiguration.java 以及子配置類 JdbcConfig.java

package cn.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration//定義本類是一個配置類
@Import(JdbcConfig.class)//定義子配置類
@ComponentScan("cn.lemon")//定義註解要搜索的包
@PropertySource("classpath:/jdbc.properties")//讀取屬性文件
@EnableTransactionManagement(proxyTargetClass = true)//開啓事務對註解的支持,,子類代理,不寫的話爲接口代理
public class SpringConfiguration {
}
package cn.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


@Configuration//定義本類是一個配置類,是可以省略的
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
// *  Bean
// *      作用:用於把當前方法的返回值作+爲bean對象存入spring的ioc容器中
// *      屬性:
//             name:用於指定bean的id。當不寫時,默認值是當前方法的名稱
// *      細節:
//             當我們使用註解配置方法時,如果方法有參數,spring框架會去容器中查找有沒有可用的bean對象。
//             查找的方式和Autowired註解的作用是一樣的

    @Bean
    public DataSource dataSource() {// 在spring 中產生對象
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {//配置事務管理器
        return new DataSourceTransactionManager(dataSource);
    }
}

第三步:修改測試類

package cn.lemon.service.impl;

import cn.config.SpringConfiguration;
import cn.lemon.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceImplTest {
    @Autowired
    private IAccountService iAccountService;

    @Test
    public void transfer() {
        iAccountService.transfer(2,1,100d);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章