spring—事務控制

編程式事務控制相關對象

PlatformTransactionManager

PlatformTransactionManager 接口是 spring 的事務管理器,它里面提供了我們常用的操作事務的方法。注意:

PlatformTransactionManager 是接口類型,不同的 Dao 層技術則有不同的實現類
例如:Dao 層技術是jdbc 或 mybatis 時:org.springframework.jdbc.datasource.DataSourceTransactionManager

Dao 層技術是hibernate時:org.springframework.orm.hibernate5.HibernateTransactionManager

TransactionDefinition

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

事務隔離級別

設置隔離級別,可以解決事務并發產生的問題,如臟讀、不可重復讀和虛讀。

  • ISOLATION_DEFAULT

  • ISOLATION_READ_UNCOMMITTED

  • ISOLATION_READ_COMMITTED

  • ISOLATION_REPEATABLE_READ

  • ISOLATION_SERIALIZABLE

事務傳播行為

  • REQUIRED:如果當前沒有事務,就新建一個事務,如果已經存在一個事務中,加入到這個事務中。一般的選擇(默認值)

  • SUPPORTS:支持當前事務,如果當前沒有事務,就以非事務方式執行(沒有事務)

  • MANDATORY:使用當前的事務,如果當前沒有事務,就拋出異常

  • REQUERS_NEW:新建事務,如果當前在事務中,把當前事務掛起。

  • NOT_SUPPORTED:以非事務方式執行操作,如果當前存在事務,就把當前事務掛起

  • NEVER:以非事務方式運行,如果當前存在事務,拋出異常

  • NESTED:如果當前存在事務,則在嵌套事務內執行。如果當前沒有事務,則執行 REQUIRED 類似的操作

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

  • 是否只讀:建議查詢時設置為只讀

TransactionStatus

TransactionStatus 接口提供的是事務具體的運行狀態

基于 XML 的聲明式事務控制

什么是聲明式事務控制

Spring 的聲明式事務顧名思義就是采用聲明的方式來處理事務。這里所說的聲明,就是指在配置文件中聲明,用在 Spring 配置文件中聲明式的處理事務來代替代碼式的處理事務。

聲明式事務處理的作用

  • 事務管理不侵入開發的組件。具體來說,業務邏輯對象就不會意識到正在事務管理之中,事實上也應該如此,因為事務管理是屬于系統層面的服務,而不是業務邏輯的一部分,如果想要改變事務管理策劃的話,也只需要在定義文件中重新配置即可

  • 在不需要事務管理的時候,只要在設定文件上修改一下,即可移去事務管理服務,無需改變代碼重新編譯,這樣維護起來極其方便

注意:Spring 聲明式事務控制底層就是AOP。

聲明式事務控制的實現

①引入tx命名空間

<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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:p="http://www.springframework.org/schema/p"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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">

②配置事務增強
③配置事務 AOP 織入

    <bean id="txm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="datasource"/></bean><tx:advice id="interceptor" transaction-manager="txm"><tx:attributes><tx:method name="save" isolation="DEFAULT" propagation="REQUIRED" timeout="-1" read-only="false"/></tx:attributes></tx:advice><aop:config><aop:pointcut id="pc" expression="execution( void com.ImplService.*(..))"/><aop:advisor advice-ref="interceptor" pointcut-ref="pc"/></aop:config>

④測試事務控制轉賬業務代碼

@Service("service")
@Scope("singleton")
public class ImplService implements com.Service {@Autowired@Qualifier("impl")ImplDao dao;public void save() {dao.out();dao.in();}}
@Repository("impl")
@Scope("singleton")
public class ImplDao implements Dao {@AutowiredJdbcTemplate jdbcTemplate;public void save() {System.out.println("saving");}public void in(){jdbcTemplate.update("update account set money=money+500 where name='tony'");}public void out(){jdbcTemplate.update("update account set money=money-500 where name='john'");}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {@AutowiredService service;@Testpublic void test(){service.save();}}

切點方法的事務參數的配置

<!--事務增強配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="*"/></tx:attributes>
</tx:advice>

其中,tx:method 代表切點方法的事務參數的配置,例如:

<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="-1" read-only="false"/>
  • name:切點方法名稱

  • isolation:事務的隔離級別

  • propogation:事務的傳播行為

  • timeout:超時時間

  • read-only:是否只讀

基于注解的聲明式事務控制

@Service("service")
@Scope("singleton")
public class ImplService implements com.Service {@Autowired@Qualifier("impl")ImplDao dao;@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,timeout = -1,readOnly = false)public void save() {dao.out();/* int i=1/0;*/dao.in();}}
@Repository("impl")
@Scope("singleton")
public class ImplDao implements Dao {@AutowiredJdbcTemplate jdbcTemplate;public void save() {System.out.println("saving");}public void in(){jdbcTemplate.update("update account set money=money+500 where name='tony'");}public void out(){jdbcTemplate.update("update account set money=money-500 where name='john'");}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {@AutowiredService service;@Testpublic void test(){service.save();}}
<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:p="http://www.springframework.org/schema/p"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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
"><context:property-placeholder location="jdbc.properties"/><context:component-scan base-package="com"/><tx:annotation-driven transaction-manager="txm"/><bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="datasource"/></bean><bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><bean id="txm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="datasource"/></bean></beans>

注解配置聲明式事務控制解析

①使用 @Transactional 在需要進行事務控制的類或是方法上修飾,注解可用的屬性同 xml 配置方式,例如隔離級別、傳播行為等。

②注解使用在類上,那么該類下的所有方法都使用同一套注解參數配置。

③使用在方法上,不同的方法可以采用不同的事務參數配置。

④Xml配置文件中要開啟事務的注解驅動<tx:annotation-driven />

知識要點

注解聲明式事務控制的配置要點

  • 平臺事務管理器配置(xml方式)

  • 事務通知的配置(@Transactional注解配置)

  • 事務注解驅動的配置 tx:annotation-driven/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391904.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391904.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391904.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

為什么印度盛產碼農_印度農產品價格的時間序列分析

為什么印度盛產碼農Agriculture is at the center of Indian economy and any major change in the sector leads to a multiplier effect on the entire economy. With around 17% contribution to the Gross Domestic Product (GDP), it provides employment to more than 50…

SAP NetWeaver

SAP的新一代企業級服務架構——NetWeaver    SAP NetWeaver是下一代基于服務的平臺&#xff0c;它將作為未來所有SAP應用程序的基礎。NetWeaver包含了一個門戶框架&#xff0c;商業智能和報表&#xff0c;商業流程管理&#xff08;BPM&#xff09;&#xff0c;自主數據管理&a…

NotifyMyFrontEnd 函數背后的數據緩沖區(一)

async.c的 static void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid) 函數中的主要邏輯是這樣的&#xff1a;復制代碼if (whereToSendOutput DestRemote) { StringInfoData buf; pq_beginmessage(&buf, A); //cursor 為 A pq…

最后期限 軟件工程_如何在軟件開發的最后期限內實現和平

最后期限 軟件工程D E A D L I N E…最后期限… As a developer, this is one of your biggest nightmares or should I say your enemy? Name it whatever you want.作為開發人員&#xff0c;這是您最大的噩夢之一&#xff0c;還是我應該說您的敵人&#xff1f; 隨便命名。 …

SQL Server的復合索引學習【轉載】

概要什么是單一索引,什么又是復合索引呢? 何時新建復合索引&#xff0c;復合索引又需要注意些什么呢&#xff1f;本篇文章主要是對網上一些討論的總結。一.概念單一索引是指索引列為一列的情況,即新建索引的語句只實施在一列上。用戶可以在多個列上建立索引&#xff0c;這種索…

leetcode 1423. 可獲得的最大點數(滑動窗口)

幾張卡牌 排成一行&#xff0c;每張卡牌都有一個對應的點數。點數由整數數組 cardPoints 給出。 每次行動&#xff0c;你可以從行的開頭或者末尾拿一張卡牌&#xff0c;最終你必須正好拿 k 張卡牌。 你的點數就是你拿到手中的所有卡牌的點數之和。 給你一個整數數組 cardPoi…

pandas處理excel文件和csv文件

一、csv文件 csv以純文本形式存儲表格數據 pd.read_csv(文件名)&#xff0c;可添加參數enginepython,encodinggbk 一般來說&#xff0c;windows系統的默認編碼為gbk&#xff0c;可在cmd窗口通過chcp查看活動頁代碼&#xff0c;936即代表gb2312。 例如我的電腦默認編碼時gb2312&…

tukey檢測_回到數據分析的未來:Tukey真空度的整潔實現

tukey檢測One of John Tukey’s landmark papers, “The Future of Data Analysis”, contains a set of analytical techniques that have gone largely unnoticed, as if they’re hiding in plain sight.John Tukey的標志性論文之一&#xff0c;“ 數據分析的未來 ”&#x…

spring— Spring與Web環境集成

ApplicationContext應用上下文獲取方式 應用上下文對象是通過new ClasspathXmlApplicationContext(spring配置文件) 方式獲取的&#xff0c;但是每次從容器中獲 得Bean時都要編寫new ClasspathXmlApplicationContext(spring配置文件) &#xff0c;這樣的弊端是配置文件加載多次…

Elasticsearch集群知識筆記

Elasticsearch集群知識筆記 Elasticsearch內部提供了一個rest接口用于查看集群內部的健康狀況&#xff1a; curl -XGET http://localhost:9200/_cluster/healthresponse結果&#xff1a; {"cluster_name": "format-es","status": "green&qu…

Item 14 In public classes, use accessor methods, not public fields

在public類中使用訪問方法&#xff0c;而非公有域 這標題看起來真晦澀。。解釋一下就是&#xff0c;如果類變成public的了--->那就使用getter和setter&#xff0c;不要用public成員。 要注意它的前提&#xff0c;如果是private的class&#xff08;內部類..&#xff09;或者p…

子集和與一個整數相等算法_背包問題的一個變體:如何解決Java中的分區相等子集和問題...

子集和與一個整數相等算法by Fabian Terh由Fabian Terh Previously, I wrote about solving the Knapsack Problem (KP) with dynamic programming. You can read about it here.之前&#xff0c;我寫過有關使用動態編程解決背包問題(KP)的文章。 你可以在這里閱讀 。 Today …

matplotlib圖表介紹

Matplotlib 是一個python 的繪圖庫&#xff0c;主要用于生成2D圖表。 常用到的是matplotlib中的pyplot&#xff0c;導入方式import matplotlib.pyplot as plt 一、顯示圖表的模式 1.plt.show() 該方式每次都需要手動show()才能顯示圖表&#xff0c;由于pycharm不支持魔法函數&a…

到2025年將保持不變的熱門流行技術

重點 (Top highlight)I spent a good amount of time interviewing SMEs, data scientists, business analysts, leads & their customers, programmers, data enthusiasts and experts from various domains across the globe to identify & put together a list that…

spring—SpringMVC的請求和響應

SpringMVC的數據響應-數據響應方式 頁面跳轉 直接返回字符串 RequestMapping(value {"/qq"},method {RequestMethod.GET},params {"name"})public String method(){System.out.println("controller");return "success";}<bea…

Maven+eclipse快速入門

1.eclipse下載 在無外網情況下&#xff0c;無法通過eclipse自帶的help-install new software輸入url來獲取maven插件&#xff0c;因此可以用集成了maven插件的免安裝eclipse(百度一下有很多)。 2.jdk下載以及環境變量配置 JDK是向前兼容的&#xff0c;可在Eclipse上選擇編譯器版…

源碼閱讀中的收獲

最近在做短視頻相關的模塊&#xff0c;于是在看 GPUImage 的源碼。其實有一定了解的伙伴一定知道 GPUImage 是通過 addTarget 鏈條的形式添加每一個環節。在對于這樣的設計贊嘆之余&#xff0c;想到了實際開發場景下可以用到的場景&#xff0c;借此分享。 我們的項目中應該有很…

馬爾科夫鏈蒙特卡洛_蒙特卡洛·馬可夫鏈

馬爾科夫鏈蒙特卡洛A Monte Carlo Markov Chain (MCMC) is a model describing a sequence of possible events where the probability of each event depends only on the state attained in the previous event. MCMC have a wide array of applications, the most common of…

PAT乙級1012

題目鏈接 https://pintia.cn/problem-sets/994805260223102976/problems/994805311146147840 題解 就比較簡單&#xff0c;判斷每個數字是哪種情況&#xff0c;然后進行相應的計算即可。 下面的代碼中其實數組是不必要的&#xff0c;每取一個數字就可以直接進行相應計算。 // P…

我如何在昌迪加爾大學中心組織Google Hash Code 2019

by Neeraj Negi由Neeraj Negi 我如何在昌迪加爾大學中心組織Google Hash Code 2019 (How I organized Google Hash Code 2019 at Chandigarh University Hub) This is me !!! Neeraj Negi — Google HashCode Organizer這就是我 &#xff01;&#xff01;&#xff01; Neeraj …