spring框架學習筆記7:事務管理及案例

来源:https://www.cnblogs.com/xuyiqing/archive/2018/02/24/8465095.html
-Advertisement-
Play Games

Spring提供了一套管理項目中的事務的機制 以前寫過一篇簡單的介紹事務的隨筆:http://www.cnblogs.com/xuyiqing/p/8430214.html 還有一篇Hibernate的事務管理:http://www.cnblogs.com/xuyiqing/p/8449167.ht ...


Spring提供了一套管理項目中的事務的機制

以前寫過一篇簡單的介紹事務的隨筆:http://www.cnblogs.com/xuyiqing/p/8430214.html

還有一篇Hibernate的事務管理:http://www.cnblogs.com/xuyiqing/p/8449167.html

可以做個對比

 

Spring管理事務特有的屬性:

事務傳播行為:事務傳播行為(propagation behavior)指的就是當一個事務方法被另一個事務方法調用時,這個事務方法應該如何進行。 

例如:methodA事務方法調用methodB事務方法時,methodB是繼續在調用者methodA的事務中運行呢,還是為自己開啟一個新事務運行,這就是由methodB的事務傳播行為決定的。

 

1、PROPAGATION_REQUIRED:如果當前沒有事務,就創建一個新事務,如果當前存在事務,就加入該事務,該設置是最常用的設置

2、PROPAGATION_SUPPORTS:支持當前事務,如果當前存在事務,就加入該事務,如果當前不存在事務,就以非事務執行。‘

3、PROPAGATION_MANDATORY:支持當前事務,如果當前存在事務,就加入該事務,如果當前不存在事務,就拋出異常。

4、PROPAGATION_REQUIRES_NEW:創建新事務,無論當前存不存在事務,都創建新事務。

5、PROPAGATION_NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起。

6、PROPAGATION_NEVER:以非事務方式執行,如果當前存在事務,則拋出異常。

7、PROPAGATION_NESTED:如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則執行與PROPAGATION_REQUIRED類似的操作

 

 

接下來演示事務案例:簡單模擬轉賬

需要的包:

新建一張表,放入數據:

package dao;

public interface AccountDao {
    
    //加錢
    void increaseMoney(Integer id,Double money);
    //減錢
    void decreaseMoney(Integer id,Double money);
}
package dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao  {

    @Override
    public void increaseMoney(Integer id, Double money) {
        
        getJdbcTemplate().update("update t_account set money = money+? where id = ? ", money,id);
        
    }

    @Override
    public void decreaseMoney(Integer id, Double money) {

        getJdbcTemplate().update("update t_account set money = money-? where id = ? ", money,id);
    }

}
package service;

public interface AccountService {
    
    //轉賬方法
    void transfer(Integer from,Integer to,Double money);
    
}
package service;

import dao.AccountDao;

public class AccountServiceImpl implements AccountService {

    private AccountDao ad;

    @Override
    public void transfer(final Integer from, final Integer to, final Double money) {
        // 減錢
        ad.decreaseMoney(from, money);
        // 加錢
        ad.increaseMoney(to, money);
    }

    public void setAd(AccountDao ad) {
        this.ad = ad;
    }

}
package tx;

import javax.annotation.Resource;

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

import service.AccountService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
        @Resource(name="accountService")
    private AccountService as;
    
    @Test
    public void fun1(){
        
        as.transfer(1, 2, 100d);
        
    }
}

配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

<!-- 指定spring讀取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 事務核心管理器,封裝了所有事務操作. 依賴於連接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 配置事務通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
        <!-- 以方法為單位,指定方法應用什麼事務屬性
            isolation:隔離級別
            propagation:傳播行為
            read-only:是否只讀
            其他方法的配置沒有用到,但它們通常是統一配置
         -->
        <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
        <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
        
        <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
    </tx:attributes>
</tx:advice>


<!-- 配置織入 -->
<aop:config  >
    <!-- 配置切點表達式 -->
    <aop:pointcut expression="execution(* service.*ServiceImpl.*(..))" id="txPc"/>
    <!-- 配置切麵 : 通知+切點
             advice-ref:通知的名稱
             pointcut-ref:切點的名稱
     -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config>


<!-- 1.將連接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>



<!-- 2.Dao-->
<bean name="accountDao" class="dao.AccountDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
</bean>  

</beans>

db.properties

jdbc.jdbcUrl=jdbc:mysql:///mybase
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=xuyiqing

 

運行Demo後結果:

 

轉賬成功!

 

補充:

可以採用註解方式代替XML配置文件:

配置文件只要一行即可:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">

<!-- 指定spring讀取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />

<!-- 事務核心管理器,封裝了所有事務操作. 依賴於連接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 事務模板對象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
    <property name="transactionManager" ref="transactionManager" ></property>
</bean>

<!-- 開啟使用註解管理aop事務 -->
<tx:annotation-driven/>

<!-- 1.將連接池 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
    <property name="driverClass" value="${jdbc.driverClass}" ></property>
    <property name="user" value="${jdbc.user}" ></property>
    <property name="password" value="${jdbc.password}" ></property>
</bean>



<!-- 2.Dao-->
<bean name="accountDao" class="dao.AccountDaoImpl" >
    <property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.Service-->
<bean name="accountService" class="service.AccountServiceImpl" >
    <property name="ad" ref="accountDao" ></property>
</bean>  

</beans>
package service;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import dao.AccountDao;

@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = true)
public class AccountServiceImpl implements AccountService {

    private AccountDao ad;

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, readOnly = false)
    public void transfer(final Integer from, final Integer to, final Double money) {
        // 減錢
        ad.decreaseMoney(from, money);
        // 加錢
        ad.increaseMoney(to, money);
    }

    public void setAd(AccountDao ad) {
        this.ad = ad;
    }

}

 

 

測試後同樣成功!

Spring框架的學習就到這裡


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

-Advertisement-
Play Games
更多相關文章
  • 前言 為了鞏固MVC的開發模式,下麵就寫一個購物車的小案例.. ①構建開發環境 導入需要用到的開發包 建立程式開發包 ②設計實體 書籍實體 購物車與購物項實體 可能我們會這樣設計購物車 上面的做法是不合適的,試想一下: 如果我要購買兩本相同的書,購物車的頁面上就出現了兩本書,而不是書 2。買三本相同 ...
  • Django中的CBV和FBV 一、 CBV CBV是採用面向對象的方法寫視圖文件。 CBV的執行流程: 瀏覽器向伺服器端發送請求,伺服器端的urls.py根據請求匹配url,找到要執行的視圖類,執行dispatch方法區分出是POST請求還是GET請求,執行views.py對應類中的POST方法或 ...
  • 匿名內部類是內部類的簡寫格式。 定義匿名內部類的前提: 內部類必須是繼承一個類或者實現一個介面。 匿名內部類的格式: 其實匿名內部類就是一個匿名子類對象,就是把定義類和建立對象封裝在一起的一種表現形式,形成的是匿名子類對象。 ...
  • auto關鍵字:1.C++98標準auto關鍵字的作用和C語言的相同,表示自動變數,是關於變數存儲位置的類型飾詞,通常不寫,因為局部變數的預設存儲就是auto 2.C++11標準中auto關鍵字不再表示變數的存儲類型,而是用於類型推導 (2.1)auto的基本用法 (2.2)auto和指針或者引用結 ...
  • 前言 很多項目, 都不是一個系統就做完了. 而是好多個系統, 相互協作來完成功能. 那, 系統與系統之間, 不可能完全獨立吧? 如: 在學校所用的管理系統中, 有學生系統, 資產系統, 宿舍系統等等. 當學期結束之後, 是否需要對已經結束的期次進行歸檔操作. 假如歸檔功能在學生系統中, 那點擊歸檔之 ...
  • final關鍵字的含義 在`Java final`,你將不能改變這個引用了,編譯器會檢查代碼,如果你試圖將變數再次初始化的話,編譯器會報編譯錯誤。 final變數 凡是對成員變數或者本地變數(在方法中的或者代碼塊中的變數稱為本地變數)聲明為 的都叫作 變數。 變數經常和 關鍵字一起使用,作為常量。 ...
  • 1. Scrapy框架 Scrapy是python下實現爬蟲功能的框架,能夠將數據解析、數據處理、數據存儲合為一體功能的爬蟲框架。 2. Scrapy安裝 1. 安裝依賴包 2. 安裝scrapy 註意事項:scrapy和twisted存在相容性問題,如果安裝twisted版本過高,運行scrapy ...
  • RuntimeException也可以給throws 非運行異常(編譯異常)throw 一定需要throws 異常,以待捕獲或繼續拋出,是因為運行時異常一旦發生,程式會停止 運行時異常 jvm會自動補throws,所以不寫也不會出錯,寫上也行 子父類異常問題 子類異常不能大於父類異常 父類無異常,子 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...