springboot有关事务的实现

一、事务
1.事务的概念

事务是指一组操作,这些操作要么全部成功,要么全部失败。如果在一组操作中有一个操作失败了,那么整个事务都应该回滚,即撤销已经执行的操作,从而保证数据的一致性和完整性。

2.事务的四个特性(ACID 特性)
  • Atomicity(原子性):事务的所有操作要么全部成功,要么全部失败。
  • Consistency(一致性):事务执行前后,数据的完整性和一致性保持不变。
  • Isolation(隔离性):事务的执行不受其他事务的干扰,即并发执行的事务之间应该相互隔离。
  • Durability(持久性):事务提交后,它的结果应该永久保存在数据库中。
3.Spring Boot 中的事务

在 Spring Boot 中,我们可以使用事务管理器来管理事务。事务管理器可以确保一系列操作要么全部成功,要么全部失败,从而保证数据的一致性和完整性。

Spring Boot 中的事务管理器是通过 AOP(面向切面编程)实现的,它可以拦截带有 @Transactional 注解的方法,并在方法执行前后自动开启和提交事务。如果方法执行过程中发生异常,事务管理器会自动回滚事务,从而保证数据的一致性和完整性。

二、IDEA具体实现(在springBoot进行事务管理)

1.开启事务

@EnableTransactionManagement

2.设置事务

@Transactional(isolation = Isolation.DEFAULT)

@Transactional(propagation = Propagation.REQUIRED)

1.在启动类中添加开始事务注解@EnableTransactionManagement
复制代码
@SpringBootApplication
@EnableTransactionManagement
public class SpringbootCenter01TxApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootCenter01TxApplication.class, args);
    }

}
2.在需要开启事物的方法上面添加设置事务注解@Transactional
复制代码
@Service
public class CustomerServiceImp  implements ICustomerService{

    @Autowired
    CustomerMapper dao;

    @Transactional
    @Override
    public void add() {
        dao.insert(new Customer("西安","五星级","ypp"));
        int a=10/0;
        dao.insert(new Customer("宝鸡","五星级","kyz"));
    }
}
3.Controller层代码
复制代码
@RestController
//@Controller
public class CustomerController {
    @Autowired
    ICustomerService service;
    
    //@ResponseBody
    @RequestMapping("/add")
    public String add() {
        service.add();
        return "成功";
    }
}
相关推荐
Wang's Blog1 天前
Go-Zero项目开发4: 用户服务搜索、详情与统一错误处理
开发语言·golang
<小智>1 天前
及时做APP开发实战(十二)-LazyForEach懒加载优化实践
数据库·鸿蒙
我星期八休息1 天前
网络编程—应用层HTTP协议
linux·运维·开发语言·前端·网络·网络协议·http
龙仔7251 天前
人大金仓KingbaseES V8 手动单库备份&恢复操作笔记
数据库·笔记·oracle·人大金仓
梅雅达编程笔记1 天前
零基础学 Python 第14章 | 模块、包与第三方库
开发语言·python·django·numpy·pandas
Mr__Miss1 天前
Java泛型完全指南:从入门到精通
java·开发语言·python
赵庆明老师1 天前
Vben精讲:14-Vben远程加载语言包
开发语言·vben
jinyishu_1 天前
模拟实现 C++ 栈和队列——从适配器模式看懂 STL 容器之美
java·c++·适配器模式
hehelm1 天前
AI大模型接入SDK—通用模块设计
linux·开发语言·c++
前端工作日常1 天前
我学习到的Java类和对象区别
java·后端