”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 理解Spring Boot中的@Transactional

理解Spring Boot中的@Transactional

发布于2024-07-29
浏览:618

Understanding @Transactional in Spring Boot

在Spring Boot中管理事务可以使用@Transactional注解来完成。在这篇博文中,我们将探讨如何使用 @Transactional 来确保数据一致性并简化 Spring Boot 应用程序中的错误处理。

1. 基本使用

要使用@Transactional,您通常将其放置在您想要事务行为的服务类的方法上。

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService{

    @Transactional
    public void createUser() {
        // enter your transactional code here
    }
}

2. 传播和隔离级别

您可以指定事务的传播和隔离级别来控制事务的行为方式:

  • 传播:定义现有事务已在运行时事务的行为方式。

  • 隔离:定义事务的数据可见性级别。

@Transactional(propagation = Propagation.REQUIRED, 
              isolation = Isolation.READ_COMMITTED)
public void createUser() {
    // enter your transactional code here
}

3. 回滚规则

您可以指定哪些异常应触发回滚:

@Transactional(rollbackFor = Exception.class)
public void createUser() {
    // your transactional code here
}

4. 只读事务

如果你的方法只读取数据,不执行任何写操作,可以将其标记为只读以优化性能:

@Transactional(readOnly = true)
public void getUser() {
    // your read-only code here
}

5. 类的事务性

您还可以将@Transactional放置在类级别,将其应用到类中的所有方法:

@Service
@Transactional
public class UserService {

    public void getUser() {
        // transactional code
    }

    public void createUser() {
        // transactional code
    }
}

具有事务方法的示例服务

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {

    @Transactional
    public void saveUser() {
        // code to save data
    }

    @Transactional(readOnly = true)
    public void fetchUser() {
        // code to fetch data
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void newTransaction() {
        // code to execute in a new transaction
    }

    @Transactional(rollbackFor = {CustomException.class})
    public void performWithRollback() {
        // risky code that may throw CustomException
    }
}

概括

使用 @Transactional Spring Boot 允许您以声明方式管理事务,准确指定您希望事务在各种场景中的行为方式。这有助于确保数据一致性并简化应用程序中的错误处理。

参考

https://www.baeldung.com/spring-transactions-read-only

https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html

Github: https://github.com/tharindu1998/transactional-blog

版本声明 本文转载于:https://dev.to/tharindufdo/understanding-transactional-in-spring-boot-8ce?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • `console.log`显示修改后对象值异常的原因
    `console.log`显示修改后对象值异常的原因
    foo = [{id:1},{id:2},{id:3},{id:4},{id:id:5},],]; console.log('foo1',foo,foo.length); foo.splice(2,1); console.log('foo2', foo, foo....
    编程 发布于2025-05-01
  • 如何使用Depimal.parse()中的指数表示法中的数字?
    如何使用Depimal.parse()中的指数表示法中的数字?
    在尝试使用Decimal.parse(“ 1.2345e-02”中的指数符号表示法表示的字符串时,您可能会遇到错误。这是因为默认解析方法无法识别指数符号。 成功解析这样的字符串,您需要明确指定它代表浮点数。您可以使用numbersTyles.Float样式进行此操作,如下所示:[&& && && ...
    编程 发布于2025-05-01
  • JavaScript计算两个日期之间天数的方法
    JavaScript计算两个日期之间天数的方法
    How to Calculate the Difference Between Dates in JavascriptAs you attempt to determine the difference between two dates in Javascript, consider this s...
    编程 发布于2025-05-01
  • 如何在Java的全屏独家模式下处理用户输入?
    如何在Java的全屏独家模式下处理用户输入?
    在Java 中,以全屏幕独立模式运行Java应用程序时,通常无法按期望的工作可能无法使用JAVA应用程序时,将用户输入在Java ProblemPassive rendering mode allows the use of KeyListener and ActionListener inter...
    编程 发布于2025-05-01
  • 如何使用“ JSON”软件包解析JSON阵列?
    如何使用“ JSON”软件包解析JSON阵列?
    parsing JSON与JSON软件包 QUALDALS:考虑以下go代码:字符串 } func main(){ datajson:=`[“ 1”,“ 2”,“ 3”]`` arr:= jsontype {} 摘要:= = json.unmarshal([] byte(...
    编程 发布于2025-05-01
  • JavaScript中如何动态访问全局变量?
    JavaScript中如何动态访问全局变量?
    在JavaScript 一种方法是使用窗口对象存储和检索变量。通过引用全局范围,可以使用其名称动态访问变量。 //一个脚本 var somevarname_10 = 20; //另一个脚本 window.all_vars = {}; window.all_vars ['somevarnam...
    编程 发布于2025-05-01
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在时间戳列上使用current_timestamp或MySQL版本中的current_timestamp或在5.6.5 此限制源于遗留实现的关注,这些限制需要对当前的_timestamp功能进行特定的实现。 创建表`foo`( `Productid` int(10)unsigned not n...
    编程 发布于2025-05-01
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-05-01
  • 如何从Google API中检索最新的jQuery库?
    如何从Google API中检索最新的jQuery库?
    从Google APIS 问题中提供的jQuery URL是版本1.2.6。对于检索最新版本,以前有一种使用特定版本编号的替代方法,它是使用以下语法:获取最新版本:未压缩)While these legacy URLs still remain in use, it is recommended ...
    编程 发布于2025-05-01
  • 如何在Java中正确显示“ DD/MM/YYYY HH:MM:SS.SS”格式的当前日期和时间?
    如何在Java中正确显示“ DD/MM/YYYY HH:MM:SS.SS”格式的当前日期和时间?
    如何在“ dd/mm/yyyy hh:mm:mm:ss.ss”格式“ gormat 解决方案:的,请访问量很大,并应为procectiquiestate的,并在整个代码上正确格式不多: java.text.simpledateformat; 导入java.util.calendar; 导入java...
    编程 发布于2025-05-01
  • 如何干净地删除匿名JavaScript事件处理程序?
    如何干净地删除匿名JavaScript事件处理程序?
    删除匿名事件侦听器将匿名事件侦听器添加到元素中会提供灵活性和简单性,但是当要删除它们时,可以构成挑战,而无需替换元素本身就可以替换一个问题。 element? element.addeventlistener(event,function(){/在这里工作/},false); 要解决此问题,请考虑...
    编程 发布于2025-05-01
  • 表单刷新后如何防止重复提交?
    表单刷新后如何防止重复提交?
    在Web开发中预防重复提交 在表格提交后刷新页面时,遇到重复提交的问题是常见的。要解决这个问题,请考虑以下方法: 想象一下具有这样的代码段,看起来像这样的代码段:)){ //数据库操作... 回声“操作完成”; 死(); } ?> ...
    编程 发布于2025-05-01
  • CSS强类型语言解析
    CSS强类型语言解析
    您可以通过其强度或弱输入的方式对编程语言进行分类的方式之一。在这里,“键入”意味着是否在编译时已知变量。一个例子是一个场景,将整数(1)添加到包含整数(“ 1”)的字符串: result = 1 "1";包含整数的字符串可能是由带有许多运动部件的复杂逻辑套件无意间生成的。它也可以是故意从单个真理...
    编程 发布于2025-05-01
  • 为什么使用Firefox后退按钮时JavaScript执行停止?
    为什么使用Firefox后退按钮时JavaScript执行停止?
    导航历史记录问题:JavaScript使用Firefox Back Back 此行为是由浏览器缓存JavaScript资源引起的。要解决此问题并确保在后续页面访问中执行脚本,Firefox用户应设置一个空功能。 警报'); }; alert('inline Alert')...
    编程 发布于2025-05-01
  • 为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    网格超过身体,用100%grid-template-columns 为什么在grid-template-colms中具有100%的显示器,当位置设置为设置的位置时,grid-template-colly修复了?问题: 考虑以下CSS和html: class =“ snippet-code”> g...
    编程 发布于2025-05-01

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3