示例:Spring JDBC 聲明式事務(xml配置形式)

聲明式事務是指在不修改源代碼的情況下通過配置applicationContext.xml自動實現事務控制,其本質是AOP環繞通知。它的觸發時機為:1、當目標方法執行成功時自動提交事務,2、當目標方法拋出運行時異常時,自動事務回滾


核心步驟示例(基于 XML 配置)

1. 添加依賴

因為是基于AOP,所以必須引入aop和aspectjweaver:

	 <!-- Spring 上下文支持 --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.3.30</version></dependency><!-- Spring JDBC 核心依賴 --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.3.30</version></dependency><!-- 數據庫驅動(以 MySQL 為例) --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency><!-- JUnit 4 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><!-- Spring Test --><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.3.30</version><scope>test</scope></dependency><!-- Spring AOP --><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.3.30</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.7</version></dependency><!--logback日志組件,spring框架默認集成--><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>1.3.12</version></dependency>

2.applicationContext.xml配置

主要步驟如下:
1、配置TransactionManager事務管理器
2、配置事務通知與事務屬性
3、為事務通知綁定ponitCut切點
例如:

<?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:contex="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd
"><!-- 加載屬性文件 --><contex:property-placeholder location="application.properties"/><!-- 配置數據源(使用DriverManagerDataSource,適用于簡單場景) --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driverClassName}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--jdbcTemplate配置--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean>   <!--1、配置事務管理器,用于事務創建、提交、回滾--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--2、事務通知配置,決定哪些方法使用事務,哪些方法不使用事務--><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><!--當目標方法符合正則表達式“batch*”時,啟用聲明式事務--><tx:method name="batch*" propagation="REQUIRED"/><!--當目標方法符合正則表達式“find*”時,不需要啟用聲明式事務--><tx:method name="find*" propagation="NOT_SUPPORTED" read-only="true" /><!--當目標方法符合正則表達式“get*”時,不需要啟用聲明式事務--><tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true" /><!--其他目標方法,根據項目需要設置啟用聲明式事務或不啟用事務--><tx:method name="*" propagation="NOT_SUPPORTED" read-only="true" /></tx:attributes></tx:advice><!--3、定義聲明式事務的作用范圍--><aop:config><aop:pointcut id="transactionPointcut" expression="execution(* com.hirain.service.*Service.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/></aop:config><bean id="employeeDao" class="com.hirain.dao.EmployeeDao"><property name="jdbcTemplate" ref="jdbcTemplate"/></bean><bean id="employeeService" class="com.hirain.service.EmployeeService"><property name="employeeDao" ref="employeeDao"/><property name="transactionManager" ref="transactionManager"/></bean>
</beans>

3. Service層代碼
package com.hirain.service;import com.hirain.dao.EmployeeDao;
import com.hirain.entity.Employee;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;public class EmployeeService {private EmployeeDao employeeDao;private DataSourceTransactionManager transactionManager;public void batchInsert() {for (int i = 0; i < 10; i++) {if (i==3){throw new RuntimeException("生成員工數據異常");}Employee employee = new Employee();employee.setEmployeeId(80+i);employee.setName("新員工"+i);employee.setDepartmentId(2l);employee.setTitle("客服");employee.setLevel(1);employeeDao.insert(employee);}}
//...getter and setter
}

4. DAO 層代碼
package com.hirain.dao;import com.hirain.entity.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;public class EmployeeDao {private JdbcTemplate jdbcTemplate;public Employee findById(long id){String sql = "select * from adm_employee where employee_id=?";Employee employee = jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<Employee>(Employee.class));return employee;}public int insert(Employee employee){String sql="insert into adm_employee (employee_id,name,department_id,title,level) values(?,?,?,?,?)";int rows = jdbcTemplate.update(sql,new Object[]{employee.getEmployeeId(),employee.getName(),employee.getDepartmentId(),employee.getTitle(),employee.getLevel()});return rows;}public int update(Employee employee){String sql="UPDATE adm_employee SET name=?,department_id=?,title=?,level=? WHERE employee_id=?";int rows = jdbcTemplate.update(sql,new Object[]{employee.getName(),employee.getDepartmentId(),employee.getTitle(),employee.getLevel(),employee.getEmployeeId()});return rows;}public int delete(long id){String sql="delete from adm_employee where employee_id=?";int rows = jdbcTemplate.update(sql,new Object[]{id});return rows;}public EmployeeDao() {}//...getter and setter
}

5.測試代碼
import com.hirain.dao.EmployeeDao;
import com.hirain.entity.Employee;
import com.hirain.service.EmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;@RunWith(SpringJUnit4ClassRunner.class) // 使用 Spring 的測試運行器
@ContextConfiguration(locations = {"classpath:applicationContext.xml"}) // 加載 Spring 配置文件
public class JDBCTemplateTest { @Autowiredprivate EmployeeService employeeService; @Testpublic void testBantchInsert() {employeeService.batchInsert();}}

關鍵配置說明

** @Transactional 注解屬性**
  • 傳播行為propagation(默認 REQUIRED)。
  • 隔離級別isolation(默認數據庫級別)。
  • 超時時間timeout(秒)。
  • 只讀事務readOnly(優化查詢)。
  • 回滾規則rollbackFor(指定觸發回滾的異常類型)。

聲明式事務 vs 編程式事務

特性聲明式事務(@Transactional)編程式事務(TransactionTemplate)
代碼侵入性低(注解聲明)高(手動控制事務邊界)
靈活性低(固定事務屬性)高(動態調整事務屬性)
適用場景大多數簡單到中等復雜度場景需要動態事務控制的復雜場景

注意事項

  1. 異常類型:默認僅 RuntimeExceptionError 觸發回滾,需通過 rollbackFor 指定其他異常。
  2. 自調用失效:在同一個類中通過 this.xxxMethod() 調用事務方法,事務可能失效(需通過代理對象調用)。
  3. 數據庫支持:事務需要數據庫引擎支持(如 MySQL 的 InnoDB)。

通過聲明式事務,開發者可以專注于業務邏輯,無需手動管理事務邊界,代碼更簡潔且易于維護。

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

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

相關文章

在vmware中ubuntu系統因為安裝了docker查不到ip地址

問題截圖&#xff1a; 根據提供的截圖信息&#xff0c;可以明確看到ens33網卡處于**物理連接斷開&#xff08;NO-CARRIER&#xff09;且接口關閉&#xff08;DOWN&#xff09;**的狀態&#xff0c;這是導致無法獲取IP地址的直接原因。以下是針對VMware虛擬機的具體解決方案&am…

51c大模型~合集121

我自己的原文哦~ https://blog.51cto.com/whaosoft/13869815 #大模型何以擅長小樣本學習&#xff1f; 這項研究給出詳細分析 近年來&#xff0c;大語言模型&#xff08;LLM&#xff09;在人工智能領域取得了突破性進展&#xff0c;成為推動自然語言處理技術發展與通用人…

Babylon.js 材質統一轉換指南:將 AssetContainer 中的所有材質轉換為 PBRMetallicRoughnessMaterial

在現代 3D 開發中&#xff0c;基于物理的渲染(PBR)已成為行業標準。本文將詳細介紹如何在 Babylon.js 中將 AssetContainer 加載的各種材質統一轉換為 PBRMetallicRoughnessMaterial&#xff0c;實現項目材質的標準化。 為什么需要材質轉換&#xff1f; PBRMetallicRoughness…

Go slice切片使用教程,一次通關!

簡介 Go 中的 切片&#xff08;slice&#xff09; 是 Go 最強大、最常用的數據結構之一。它是對數組的輕量封裝&#xff0c;比數組更靈活&#xff0c;幾乎所有的集合處理都用切片來完成。 什么是切片&#xff08;slice&#xff09; 切片是一個擁有 長度&#xff08;len&…

nodejs的包管理工具介紹,npm的介紹和安裝,npm的初始化包 ,搜索包,下載安裝包

nodejs的包管理工具介紹&#xff0c;npm的介紹和安裝&#xff0c;npm的初始化包 &#xff0c;搜索包&#xff0c;下載安裝包 &#x1f9f0; 一、Node.js 的包管理工具有哪些&#xff1f; 工具簡介是否默認特點npmNode.js 官方的包管理工具&#xff08;Node Package Manager&am…

FPGA設計 時空變換

1、時空變換基本概念 1.1、時空概念簡介 時鐘速度決定完成任務需要的時間&#xff0c;規模的大小決定完成任務所需要的空間&#xff08;資源&#xff09;&#xff0c;因此速度和規模就是FPGA中時間和空間的體現。 如果要提高FPGA的時鐘&#xff0c;每個clk內組合邏輯所能做的事…

增加首屏圖片

增加首屏圖片&#xff08;bg.jpg&#xff09; web-mobile類型打包 //index.html腳本 <div id"myDiv_1111"style"background: url(./bg.jpg) 50% 50%/ 100% auto no-repeat ; width:100%;height:100%;position:absolute;"></div> //游戲內腳本…

貪心算法~~

目錄 一、理論基礎 二、題目練習 &#xff08;1&#xff09;455. 分發餅干 &#xff08;2&#xff09;53. 最大子數組和 - 力扣 &#xff08;3&#xff09;122. 買賣股票的最佳時機 II - 力扣&#xff08;LeetCode&#xff09; &#xff08;4&#xff09;860. 檸檬水找零…

形象解釋 HTTP 的四種常見請求方式及其中的區別聯系

HTTP 的常見請求方式常見的有四種&#xff1a;GET、POST、PUT、DELETE&#xff0c;它們各自的功能不一樣。 &#x1f35c; 場景比喻&#xff1a;HTTP 請求像“去餐廳點菜” 請求方式行為餐廳比喻說明GET獲取數據看菜單/問服務員&#xff1a;你們有什么菜&#xff1f;不帶食材、…

string的基本使用

string的模擬實現 string的基本用法string的遍歷&#xff08;三種方式&#xff09;&#xff1a;關于auto&#xff08;自動推導&#xff09;:范圍for: 迭代器普通迭代器(可讀可改&#xff09;const迭代器&#xff08;可讀不可改&#xff09; string細小知識點string的常見接口引…

kubernetes》》k8s》》證書有效期

cd /etc/kubernetes/pki openssl x509 -in apiserver.crt -text -noount通常&#xff0c;Kubernetes的證書是由kubeadm生成的&#xff0c;所以可能需要修改kubeadm的源碼或者配置 登錄Master節點 》》》默認延續1年 # 查看證書 檢查證書有效期 # 該命令顯示 /etc/kubernetes…

LangChain LCEL表達式語言簡介

LangChain表達式語言&#xff08;LCEL&#xff09;是專為構建AI應用鏈設計的聲明式編程框架&#xff0c;通過管道符|實現組件無縫銜接&#xff0c;支持流式處理、異步調用等生產級特性。其核心優勢在于零代碼改動實現原型到生產的過渡&#xff0c;同時保持代碼簡潔性和可維護性…

【計算機視覺】CV實踐項目- 基于PaddleSeg的遙感建筑變化檢測全解析:從U-Net 3+原理到工程實踐

基于PaddleSeg的遙感建筑變化檢測全解析&#xff1a;從U-Net 3原理到工程實踐 技術背景與項目意義傳統方法的局限性深度學習的優勢 核心技術與算法原理U-Net 3架構創新全尺度跳躍連接深度監督機制 變化檢測技術路線 實戰指南&#xff1a;從環境搭建到模型部署環境配置數據準備與…

萬字長文 | Apache SeaTunnel 分離集群模式部署 K8s 集群實踐

文章作者&#xff1a;雷寶鑫 整理排版&#xff1a;白鯨開源 曾輝 Apache SeaTunnel官網鏈接: https://seatunnel.apache.org/ Apache SeaTunnel(以下簡稱SeaTunnel&#xff09;是一款新一代高性能、分布式的數據集成同步工具&#xff0c;正受到業界廣泛關注和應用。SeaTunnel支…

深入解析YOLO v1:實時目標檢測的開山之作

目錄 YOLO v1 算法詳解? ?1. 核心思想? ?2. 算法優勢? ?3. 網絡結構&#xff08;Unified Detection&#xff09;?? ?4. 關鍵創新? ?5. 結構示意圖&#xff08;Fig1&#xff09;? Confidence Score 的計算? 類別概率與 Bounding Box 的關系? 后處理&…

信令與流程分析

WebRTC是h5支持的重要特征之一&#xff0c;有了它&#xff0c;不再需要借助音視頻相關的客戶端&#xff0c;直接通過瀏覽器的Web頁面就可以實現音視頻聊天功能。 WebRTC項目是開源的&#xff0c;我們可以借助WebRTC&#xff0c;構建自己的音視頻聊緹娜功能。無論是前端JS的Web…

BIOS主板(非UEFI)安裝fedora42的方法

BIOS主板(非UEFI)安裝fedora42的方法 現實困難&#xff1a;將Fedora-Workstation-Live-42-1.1.x86_64.iso寫入U盤制作成可啟動U盤啟動fedora42&#xff0c;按照向導將fedora42安裝到真機的sda7分區中得到報錯如下內容&#xff1a; /boot/efi 必需的 /boot/efi必須位于格式化為e…

安卓 Compose 相對傳統 View 的優勢

安卓 Compose 相對傳統 View 的優勢 文章目錄 安卓 Compose 相對傳統 View 的優勢1. 引言2. 核心概念&#xff1a;Compose的革新性設計2.1 Jetpack Compose2.2 傳統安卓View系統 3. 開發體驗&#xff1a;Compose大幅提升效率3.1 使用Jetpack Compose構建UI3.2 使用傳統View系統…

SIEMENS PLC 程序 GRAPH 程序解讀 車型入庫

1、程序載圖1 2、程序截圖2 3、程序解釋 這是一個基于西門子 GRAPH 編程的車型 1 入庫順序控制流程圖&#xff0c;通過狀態機結構&#xff08;狀態框 S 與轉移條件 T&#xff09;描述完整工作流程&#xff0c;具體如下&#xff1a; 整體流程概述 初始化&#xff1a;從 S1&am…

VuePress可以做什么?

VuePress 可以做什么 VuePress 是一個基于 Vue.js 的靜態站點生成器,專注于文檔和內容展示。它結合了 Markdown 的簡潔性和 Vue 的靈活性,適合多種場景的開發需求。以下是 VuePress 的主要用途和功能: 1. 技術文檔網站 VuePress 最初是為編寫 Vue.js 官方文檔而設計的,因…