Spring 事務管理的使用

来源:https://www.cnblogs.com/chy18883701161/archive/2020/01/28/12239011.html
-Advertisement-
Play Games

Spring提供了2種事務管理 編程式的 聲明式的(重點):包括xml方式、註解方式(推薦) 基於轉賬的demo dao層 新建包com.chy.dao,包下新建介面AccountDao、實現類AccountDaoImpl: public interface AccountDao { //查詢用戶賬 ...


 

Spring提供了2種事務管理

  • 編程式的
  • 聲明式的(重點):包括xml方式、註解方式(推薦)

 

 


 

 

基於轉賬的demo

dao層

新建包com.chy.dao,包下新建介面AccountDao、實現類AccountDaoImpl:

public interface AccountDao {
    //查詢用戶賬戶上的餘額
    public double queryMoney(int id);
    //減少用戶賬戶上的餘額
    public void reduceMoney(int id, double amount);
    //增加用戶賬戶上的餘額
    public void addMoney(int id, double amount);
}
@Repository
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    @Override
    public double queryMoney(int id) {
        String sql = "select money from account_tb where id=?";
        JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
        double money = jdbcTemplate.queryForObject(sql, double.class,id);
        return money;
    }

    @Override
    public void reduceMoney(int id, double account) {
        double money = queryMoney(id);
        money -= account;
        if (money>=0){
            String sql = "update account_tb set money=? where id=?";
            JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
            jdbcTemplate.update(sql, money, id);
        }
        //此處省略餘額不足時的處理
    }

    @Override
    public void addMoney(int id, double account) {
        double money = queryMoney(id);
        money += account;
        String sql = "update account_tb set money=? where id=?";
        JdbcTemplate jdbcTemplate = super.getJdbcTemplate();
        jdbcTemplate.update(sql, money, id);
    }
}

 

 

service層

新建包com.chy.service,包下新建介面TransferService、實現類TransferServiceImpl:

public interface TransferService {
    public void transfer(int from,int to,double account);
}
@Service
public class TransferServiceImpl implements TransferService {
    private AccountDao accountDao;
    
    @Autowired
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public void transfer(int from, int to, double account) {
        accountDao.reduceMoney(from,account);
        // System.out.println(1/0);
        accountDao.addMoney(to,account);
    }
}

 

 

資料庫連接信息

src下新建db.properties:

#mysql數據源配置
url=jdbc:mysql://localhost:3306/my_db?serverTimezone=GMT
user=chy
password=abcd

 

 

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/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 引入資料庫配置信息 -->
    <context:property-placeholder location="db.properties" />

    <!-- 使用包掃描-->
    <context:component-scan base-package="com.chy.dao,com.chy.service" />

    <!-- 配置數據源,此處使用jdbc數據源 -->
    <bean name="jdbcDataSource" class="com.mysql.cj.jdbc.MysqlDataSource">
        <property name="url" value="${url}" />
        <property name="user" value="${user}" />
        <property name="password" value="${password}" />
    </bean>

    <!-- 配置AccountDaoImpl,註入數據源 -->
    <bean name="accountDaoImpl" class="com.chy.dao.AccountDaoImpl">
        <!--註入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>
</beans>

 

 

測試

新建包com.chy.test,包下新建主類Test:

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        TransferServiceImpl transferServiceImpl = applicationContext.getBean("transferServiceImpl", TransferServiceImpl.class);
        transferServiceImpl.transfer(1,2,1000);

 

 

以上是未使用事務管理的,將service層的這句代碼取消註釋,會出現錢轉丟的情況(對方收不到錢)。

// System.out.println(1/0);

 

 


 

 

編程式事務管理

編程式事務管理,顧名思義需要自己寫代碼。

自己寫代碼很麻煩,spring把代碼封裝在了TransactionTemplate類中,方便了很多。

 

(1)事務需要添加到業務層(service),修改TransferServiceImpl類如下:

@Service
public class TransferServiceImpl implements TransferService {
    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

    @Autowired
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Autowired
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    @Override
    public void transfer(int from, int to, double account) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                accountDao.reduceMoney(from, account);
                // System.out.println(1 / 0);
                accountDao.addMoney(to, account);
            }
        });
    }
}
  • 註入事務管理模板TransactionTemplate(成員變數+setter方法)。
  • 在處理業務的方法中寫:
transactionTemplate.execute(new TransactionCallbackWithoutResult() {  });

使用匿名內部類傳入一個TransactionCallbackWithoutResult介面類型的變數,只需實現一個方法:把原來處理業務的代理都放到這個方法中。


 

(2)在xml中配置事務管理、事務管理模板

    <!-- 配置事務管理器,此處使用JDBC的事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--註入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>

    <!-- 配置事務管理模板-->
    <bean class="org.springframework.transaction.support.TransactionTemplate">
        <!-- 註入事務管理器 -->
        <property name="transactionManager" ref="transactionManager" />
    </bean>

 

 

把下麵這句代碼取消註釋,運行,不會出現錢轉丟的情況(執行失敗,自動回滾):

// System.out.println(1/0);

 

 


 

 

聲明式事務管理(此節必看)

聲明式事務管理,不管是基於xml,還是基於註解,都有以下3個點要註意:

  • 底層是使用AOP實現的(在Spring中使用AspectJ),需要把AspectJ相關的jar包添加進來。

 

  • 因為我們的service層一般寫成介面——實現類的形式,既然實現了介面,基於動態代理的AspectJ代理的自然是介面,所以只能使用介面來聲明:
TransferService transferServiceImpl = applicationContext.getBean("transferServiceImpl", TransferService.class);

紅色標出的2處只能使用介面。

 

  • 在配置xml時有一些新手必遇到的坑,如果在配置xml文件時遇到了問題,可滑到最後面查看我寫的解決方式。

 

 


 

 

基於xml的聲明式事務管理

xml配置:

    <!-- 配置事務管理器,此處使用JDBC的事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--註入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>

    <!-- 配置增強-->
    <!-- 此處只能用id,不能用name。transaction-manager指定要引用的事務管理器 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 配置要添加事務的方法,直接寫方法名即可。可以有多個method元素,可以使用通配符* -->
            <tx:method name="transfer" />
        </tx:attributes>
    </tx:advice>

    <!-- 配置aop-->
    <aop:config>
        <!-- 配置切入點-->
        <aop:pointcut id="transferPointCut" expression="execution(* com.chy.service.TransferServiceImpl.transfer(..))"/>
        <!--指定要引用的<tx:advice>,指定切入點。切入點可以point-ref引用,也可以pointcut現配。可以有多個advisor元素。 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="transferPointCut"/>
    </aop:config>

 

 


 

 

說明

<tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT" read-only="false" />
  • propagation 指定事務的傳播行為,預設為REQUIRED

  • isolation 指定事務的隔離級別

  • read-only 是否只讀,讀=>查詢,寫=>增刪改。預設為false——讀寫。

  • timeout  事務的超時時間,-1表示永不超時。

這4個屬性一般都不用設置,使用預設值即可。當然,只查的時候,可以設置read-only="true"。

 

 

常見的3種配置方式:

            <tx:method name="transfer" />
<tx:method name="*" />
<tx:method name="save*" /> <tx:method name="find*" read-only="false"/> <tx:method name="update*" /> <tx:method name="delete*" />
  • 指定具體的方法名
  • 用*指定所有方法
  • 指定以特定字元串開頭的方法(我們寫的dao層方法一般都以這些詞開頭)

因為要配合aop使用,篩選範圍是切入點指定的方法,不是項目中所有的方法。

 

 

比如

<tx:method name="save*" />
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.chy.service.TransferServiceImpl.*(..))" />

切入點是TransferServiceImpl類中的所有方法,是在TransferServiceImpl類所有方法中找到以save開頭的所有方法,給其添加事務。

 

 


 

 

基於註解的聲明式事務管理(推薦)

(1)xml配置

    <!-- 配置事務管理器,此處使用JDBC的事務管理器-->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--註入數據源-->
        <property name="dataSource" ref="jdbcDataSource" />
    </bean>

    <!--啟用事務管理的註解,並指定要使用的事務管理器 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

 

 

(2)使用@Transactional標註

@Service
// @Transactional
public class TransferServiceImpl implements TransferService {
    private AccountDao accountDao;

    @Autowired
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    @Transactional
    public void transfer(int from, int to, double account) {
        accountDao.reduceMoney(from, account);
        // System.out.println(1 / 0);
        accountDao.addMoney(to, account);
    }
}

可以標註在業務層的實現類上,也可以標註在處理業務的方法上。

標註在類上,會給這個所有的業務方法都添加事務;標註在業務方法上,則只給這個方法添加事務。

 

 

同樣可以設置傳播行為、隔離級別、是否只讀:

@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)

 

基於註解的聲明式事務管理是最簡單的,推薦使用。

 

 


 

 

聲明式事務管理,配置xml時的坑

  • <tx:advice>、<tx:annotation-driven>的代碼提示不對、配置沒錯但仍然顯式紅色

原因:IDEA自動引入的約束不對。

IDEA會自動引入所需的約束,但spring事務管理所需的約束,IDEA引入的不對。

 

 

<?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/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

看我紅色標出的部分(需拖動滾動條查看最右邊),這是IDEA自動引入的tx的約束,這是舊版本的約束,已經無效了。

 

 

新版本的約束:

xmlns:tx="http://www.springframework.org/schema/tx"

xsi里對應的部分也要修改:

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

可以在錯誤約束的基礎上改,也可以添加。

 

 

如果沒有修改xsi中對應的部分,會報下麵的錯:

通配符的匹配很全面, 但無法找到元素 'tx:advice' 的聲明。
通配符的匹配很全面, 但無法找到元素 'tx:annotation-driven' 的聲明。

 

 

上面提供的約束是目前版本的約束,以後可能會變。最好在官方文檔中找,有2種方式:

(1)http://www.springframework.org/schema/tx/spring-tx.xsd     可修改此url查看其它約束

 

(2)如果下載了spring的壓縮包,可在schema文件夾下查看約束。

spring壓縮包的下載可參考:https://www.cnblogs.com/chy18883701161/p/11108542.html

   


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Diagrams(圖)可以理解為畫布 1:創建圖 在右側的Model Explorer管理界面的第一個節點右鍵,或者選擇菜單中Model | Add Diagram | [DiagramType]都可以創建 2:Delete Diagram 選擇後滑鼠右鍵或菜單Edit中 3:Open Diagra ...
  • 1:創建空的項目 創建項目可以按Ctrl+N或選擇菜單File| New,StarUML安裝打開後預設會有個空項目結構。 2:創建模板項目 可以通過選擇模板來啟動建模項目(會根據模板創建項目結構)。 要使用模板啟動項目,請從File| | New From TemplateName中選擇。 Star ...
  • 為什麼用StarUML UML建模工具比較常見的PowerDesigner ROSE StarUML starUML-開源免費(1-2百M),PowerDesigner-精細和一體化(6-7百M),ROSE-大而全(3-4百M) 看個人設計目的,starUML(http://staruml.io/) ...
  • 集合就像是一個購物車,可以將購買的所有商品的存放在一個統一的購物車中集合的概念現實生活: 很多的事物湊在一起數學中的集合: 具有共同屬性的事物的總體是一種工具類,是一種容器,裡面可以存儲任意數量的相同屬性的類。集合的作用在類的內部對數據進行組織簡單快速的搜索大數量的條目有的集合口,提供了一系列排列有... ...
  • 通過getchar來取代cin不斷對緩衝區的操作,加快速度 調用 即可 ...
  • 英文 | "Python Tips and Trick, You Haven't Already Seen" 原作 | Martin Heinz ( "https://martinheinz.dev" ) 譯者 | 豌豆花下貓 聲明 :本文獲得原作者授權翻譯,轉載請保留原文出處,請勿用於商業或非法用 ...
  • 這兩天新型肺炎病例是指數上升啊!呆在家裡沒事幹,正好想起之前FPGA大賽上有個老哥做了一個圖像旋轉作品,還在群里發了技術報告。無聊之下就打算學習一下,然後就順便把平移、旋轉、縮放這些幾何變換都看了,最後決定把這三個綜合起來寫個“旋轉傻烏龜”的動畫。先是用OpenCV內置函數實現了下,感覺不過癮,又自 ...
  • 軟體下載及配置 軟體下載 mvn需要jdk的支持,jdk下載地址: http://www.oracle.com/technetwork/java/javase/downloads/jdk8 downloads 2133151.html 官方下載地址:http://maven.apache.org/d ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...